从案例查询中消除空结果 - 源中没有空值

Eliminate null results from case query - no null values in source

我正在尝试执行一个复杂的聚合和串联查询来准备要导入网站的数据,将多个结果行和列聚合到每个 ID 一行中。

我快到了,除了我得到了很多 NULL 结果,尽管源数据中没有 NULL 值。

源数据:

id value_1 value_2 value_3 type
x1 sometext othertext moretext A2
x1 sometext othertext moretext B1
x1 sometext othertext moretext B2
x2 sometext othertext moretext B1
x2 sometext othertext moretext A2
x2 sometext othertext moretext B1

以下:

select distinct id, 
case when type='A2' then string_agg (concat(cast (value_1 as nvarchar (max)),value_1,value_2,value_3)) end as type_A2, 
case when type='B1' then string_agg (concat(cast (value_1 as nvarchar (max)),value_1,value_2,value_3)) end as type_B1
from source
group by id, type

产生:

id type_a2 type_B1
x1 sometextothertextmoretext NULL
x1 NULL sometextothertextmoretext
x2 sometextothertextmoretext NULL
x2 NULL sometextothertextmoretext

当我一次只尝试 运行 一列时,我仍然得到一些 NULL 结果。

如何将这些结果按唯一 ID 排成一行?

即...

id type_a2 type_B1
x1 sometextothertextmoretext sometextothertextmoretext
x2 sometextothertextmoretext sometextothertextmoretext
x3 etc etc

每个 id 需要一行 - 因此,我将从 selectgroup by 子句中删除 type 开始。接下来,case 表达式将进入 内部 聚合函数。所以:

select id,
    string_agg(case when type = 'A2' then concat(cast(value_1 as nvarchar(max)), value_1, value_2, value_3) end, ',') as type_a2,
    string_agg(case when type = 'B1' then concat(cast(value_1 as nvarchar(max)), value_1, value_2, value_3) end, ',') as type_b1
from mytable
group by id