【问题标题】:How to update rows based on one field/column of snowflake tables如何根据雪花表的一个字段/列更新行
【发布时间】:2021-10-25 07:28:41
【问题描述】:

我想使用字段“Id”上的另一个表来更新一个表,这样它就不会创建重复项

假设我的第一个表是 Table1 而第二个表是 Table2 。当 Id 匹配时,我想从 Table2 更新 Table1 中的行

我知道使用 UNION 函数,但这适用于我只需要考虑单个列的整个列。 https://docs.snowflake.com/en/sql-reference/operators-query.html#union-all

我的表格示例

表 1

Id  name    number  value
1   a        8       100
2   b        8       100
3   c        8       100
4   d        8       100

表2

Id  name    number  value
3   c         8      99
4   d         6      100
5   e         7      100

预期输出

Id  name    number  value
1   a        8       100
2   b        8       100
3   c        8        99
4   d        6       100
5   e        7       100

请注意,在输出表中,ID 为 3,4 的行已更新,并插入了新的 ID 5。有人可以通过select query 帮助我获得所需的输出吗?

【问题讨论】:

    标签: snowflake-cloud-data-platform


    【解决方案1】:

    您可以使用 MERGE 命令:

    merge into table1 using table2 on table1.id = table2.id
        when matched then 
            update set table1.name = table2.name, table1.number = table2.number, table1.value = table2.value
        when not matched then 
            insert (Id,name,number,value) values (table2.id, table2.name, table2.number, table2.value);
            
    select * from table1;
    
    +----+------+--------+-------+
    | ID | NAME | NUMBER | VALUE |
    +----+------+--------+-------+
    |  5 | e    |      7 |   100 |
    |  1 | a    |      8 |   100 |
    |  2 | b    |      8 |   100 |
    |  3 | c    |      8 |    99 |
    |  4 | d    |      6 |   100 |
    +----+------+--------+-------+
    

    https://docs.snowflake.com/en/sql-reference/sql/merge.html

    如果不想更新表,可以使用 IFNULL 和全外连接:

    select 
    IFNULL( t1.id, t2.id) id,
    IFNULL( t2.name, t1.name ) name, 
    IFNULL( t2.number, t1.number ) number,
    IFNULL( t2.value, t1.value ) value
    from table1 t1
    full join table2 t2
    on t1.id = t2.id;
    
    
    +----+------+--------+-------+
    | ID | NAME | NUMBER | VALUE |
    +----+------+--------+-------+
    |  1 | a    |      8 |   100 |
    |  2 | b    |      8 |   100 |
    |  3 | c    |      8 |    99 |
    |  4 | d    |      6 |   100 |
    |  5 | e    |      7 |   100 |
    +----+------+--------+-------+
    

    【讨论】:

    • 谢谢!!有什么方法可以使用 select 语句获得相同的输出。不改变表格
    • 添加到我的回答中
    • 非常感谢!!解决方案还不错
    猜你喜欢
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多