仅当数据匹配或 SQL 中有一个为 NULL 时才汇总行

Roll up rows only if data matches or one is NULL in SQL

我想合并 table 仅当所有列都匹配,或者不匹配的列是由于 NULLs

例如,如果我想加入 table t1,则如下所示:

 id | column1 | column2 | column3
----+---------+---------+---------
  A |  NULL   |    1    |   NULL
  B |  NULL   |    3    |    v5
  C |   v6    |   NULL  |   NULL

致 table t2 看起来像这样:

 id | column1 | column2 | column3
----+---------+---------+---------
  A |   v1    |    1    |    v2   
  A |  NULL   |    2    |    v3
  B |   v4    |   NULL  |   NULL
  C |   v7    |    4    |    v8

我希望生成的目标 table 是:

 id | column1 | column2 | column3
----+---------+---------+---------
  A |   v1    |    1    |    v2   
  A |  NULL   |    2    |    v3
  B |   v4    |    3    |    v5
  C |   v6    |   NULL  |   NULL
  C |   v7    |    4    |    v8

其中 t1 中的第 1 行和 t2 中的第 1 行 合并t1 中的第 2 行和 t2 中的第 3 行被合并,同时保留 t1t2 中没有匹配项的其他行。

这是否可以通过 COALESCE 和 FULL JOIN 或任何其他方法以某种方式实现?

尝试使用完全外部联接和 COALESCE

select table1.id,COALESCE(table1.column1, table2.column1) as column1,
COALESCE(table1.column2, table2.column2) as column2,
COALESCE(table1.column3, table2.column3) as column3 from table1 
full outer join table2 on table1.id=table2.id

嗯。 . .如果我理解正确,你想在执行 JOIN 时将 NULL 视为通配符。因此,任一 table 中的 NULL 将匹配另一个 table.

中的任何值

如果是这样,那么所有列上的 FULL JOIN(具有正确的逻辑)应该可以满足您的要求:

select t1.id,
       coalesce(t2.col1, t1.col1) as col1,
       coalesce(t2.col2, t1.col2) as col2,
       coalesce(t2.col3, t1.col3) as col3
from t1 full join
     t2
     on t1.id = t2.id and
        (t1.col1 = t2.col1 or t1.col1 is null or t2.col1 is null) and
        (t1.col2 = t2.col2 or t1.col2 is null or t2.col2 is null) and
        (t1.col3 = t2.col3 or t1.col4 is null or t2.col3 is null);