填充 NULL 并获得不同的记录

Fill NULL and get distinct record

我正在从两个不同的来源(来源 A 和来源 B)摄取数据。尽管数据可能来自两个不同的来源,但记录的 ID 可能存在于两个来源中。

问题是,有时一个来源比另一个更完整。在下面的示例中,来源 A 的 C 列为 NULL,但来源 B 有完整的记录。

我想丰富我得到完整记录的数据。

ID A B C D Source
asc123 1 2 NULL 4 Source A
asc123 1 2 3 4 Source B

最终结果应该是这样的:

ID A B C D
asc123 1 2 3 4

我尝试过这样的事情,但没有成功:

SELECT  ID
       ,A
       ,B
       ,COALESCE(A.C, B.C) AS C
       ,D
       ,Source
    FROM(
    SELECT * FROM (
        SELECT 'asc123' AS ID, 1 AS 'A', 2 AS 'B', NULL AS 'C', 4 AS 'D', 'Source A' AS 'Source'
        ) A
    UNION

    SELECT * FROM (
        SELECT 'asc123' AS ID, 1 AS 'A', 2 AS 'B', 3 AS 'C', 4 AS 'D', 'Source B' AS 'Source'
        ) B
    ) X

您可以只聚合以删除 NULL 值:

with sampledata as (
    select 'asc123' AS ID, 1 AS A, 2 AS B, NULL AS C, 4 as D, 'Source A' AS Source 
    union all
    select 'asc123' AS ID, 1 AS A, 2 AS B, 3 AS C, 4 AS D, 'Source B' AS Source
)
select Id,
  max(A)A, Max(B)B, Max(C)C, Max(D)D 
from sampledata
group by Id

另请注意,对于列别名,如果您需要使用 []"" 分隔它们,单引号用于 文字 值。