问题描述
我有两个表:表1是主表,表2是每月刷新并在之后被截断的表。因此,我想编写一个查询,使用一些匹配字段将表2中的每月新值插入表1中。我需要匹配的列是国家和名称。这是表格:
如何处理此查询才能进入绿色表格?我查看了更新和插入语句,但是找不到任何有帮助的东西。
解决方法
如何使用MERGE语句
MERGE INTO Table1 as Target
USING Table2 as Source
ON (target.Name = source.Name AND target.Country = source.Country)
WHEN MATCHED THEN UPDATE SET Age = source.Age,Gender = source.Gender
WHEN NOT MATCHED THEN INSERT (Name,Country,Age,Gender) VALUES (source.Name,source.Country,source.Age,source.Gender);
该语句的作用是在Target中查找与名称和国家/地区中的源记录匹配的记录。如果找到匹配项,则更新目标记录的年龄和性别,如果找不到匹配项,则在目标表中插入新记录。
我在SQL Server中对此进行了测试,但我认为雪花的语法相同。
您可以在Snowflake文档中阅读有关MERGE statement的信息。
,雪花语法
UPDATE
table1 AS TA
SET
TA.Age = TB.Age
FROM (SELECT TA1.country,TB1.country,TA1.name,TB1.name,TB1.Age
FROM table1 AS TA1
INNER JOIN table2 AS TB1
ON (TA1.country = TB1.country AND TA1.name= TB1.name)) TB
WHERE TA.country = TB.country
还有MySql
UPDATE
table1 AS TA
INNER JOIN table2 AS TB
ON TA.country = TB.country
AND TA.name= TB.name
SET
TA.Age = TB.Age;
,
考虑到您只需更新表1中的年龄列。
update table1 set AGE=(select distinct age from table2 t2 where t2.COUNTRY=table1.COUNTRY and t2.NAME=table1.NAME);
或
UPDATE table1 SET table1.age = table2.age FROM table1,table2 where table1.country = table2.country and table1.name = table2.name
,
此处的雪花语法有点不同。这样的事情应该起作用:
UPDATE table1 TA
SET TA.Age = TB.Age
FROM table2 TB
WHERE TA.country = TB.country
AND TA.name = TB.name;
请注意,关于Snowflake的文档非常出色。语法位于此处:https://docs.snowflake.com/en/sql-reference/sql/update.html