如何使用另一个 Table 更新一个 table 的值

How to Update Value of One table using Another Table

我有两个名为 TABLE1 和 TABLE2 的雪花表。仅当某些字段值与 table2 匹配时,我想通过 Table2 更新 Table1 的行。

表 1

Date       columnA  columnB  sum     reff
2021-09-27   1        Y      10       A
2021-09-27   2        Y      20       B
2021-09-27   3        Y      30       C
2021-09-27   4        Y      40       D
2021-09-27   5        S      8000     D

表 2

Date        columnA columnB  sum    reff
2021-09-27     5      Y      10       A
2021-09-27     2      Y      100      B
2021-09-27     3      Y      100      C
2021-09-27     4      Y      100      D
2021-09-27     6      S      8000     D

如果字段 Date, columnA, columnB, reff 在两个表中都匹配,我想更新行(行的更新应该在表 1 中)

异常输出

Date        columnA columnB  sum    reff
2021-09-27     1      Y      10       A
2021-09-27     2      Y      100      B
2021-09-27     3      Y      100      C
2021-09-27     4      Y      100      D
2021-09-27     5      S      8000     D
2021-09-27     5      Y      10       A
2021-09-27     6      S      8000     D

有人可以帮助我吗?使用 select 查询获取 Excepted output

您需要的是完全外部联接。 这将根据您的匹配条件加入行,但它会保留没有任何匹配的行(不需要在 table 1 中更新的行和 table2 中的新行).

当连接不成功时,你想使用非空的那个。 加入成功后,您想使用 table 2

中的值

我认为这应该可以解决问题:

select
    IFNULL(t2.Date, t1.Date) as Date,
    IFNULL(t2.columnA, t1.columnA) as columnA,
    IFNULL(t2.columnB, t1.columnB) as columnB,
    IFNULL(t2.sum, t1.sum) as sum,
    IFNULL(t2.reff, t1.reff) as reff
from
    Table2 t2
full outer join
    Table1 t1
    on t2.Date = t1.Date and t2.columnA = t1.columnA and t2.columnB = t1.columnB and t2.reff = t1.reff

另一种更新 table1 的方法是使用合并语句。更新匹配并在不匹配时插入记录。

Snowflake 合并也将获得预期输出:

    merge into source1 a
using source2 b
on 
 a.date = b.date and
 a.ColumnA = b.ColumnA and 
 a.ColumnB = b.ColumnB and 
 a.reff = b.reff
when matched then
    update set
        a.date = b.date,
        a.ColumnA = b.ColumnA,
        a.ColumnB = b.ColumnB,
        a.sum = b.sum,
        a.reff = b.reff
when not matched then insert
    (a.date, a.ColumnA, a.ColumnB, a.sum, a.reff) values (b.date, b.ColumnA, b.ColumnB, b.sum, b.reff);