Hologres这样子的行转列的数据 我一条id为445的过来 但是其余的字段 不想变成空?有什么办法吗 除了每个字段分开写入 ,STRING_AGG(distinct case when t3.id = 413 then t2.name end )
,STRING_AGG(distinct case when t3.id = 418 then t2.name end )
,STRING_AGG(distinct case when t3.id = 421 then t2.name end )
,STRING_AGG(distinct case when t3.id = 423 then t2.name end )
,STRING_AGG(distinct case when t3.id = 425 then t2.name end )
,STRING_AGG(distinct case when t3.id = 428 then t2.name end )
,STRING_AGG(distinct case when t3.id = 438 then t2.name end )
,STRING_AGG(distinct case when t3.id = 440 then t2.name end )
,STRING_AGG(distinct case when t3.id = 443 then t2.name end )
,STRING_AGG(distinct case when t3.id = 445 then t2.name end )
以下为热心网友提供的参考意见
你可以使用COALESCE
函数来处理这个问题。COALESCE
函数会返回第一个非空值,如果所有值都为空,则返回NULL。这样,当某个字段没有对应的值时,它不会变成空。
假设你的表名为t1
,字段名为id
和name
,你可以使用以下查询:
SELECT
COALESCE(STRING_AGG(distinct case when t3.id = 413 then t2.name end), '') AS name1,
COALESCE(STRING_AGG(distinct case when t3.id = 418 then t2.name end), '') AS name2,
COALESCE(STRING_AGG(distinct case when t3.id = 421 then t2.name end), '') AS name3,
COALESCE(STRING_AGG(distinct case when t3.id = 423 then t2.name end), '') AS name4,
COALESCE(STRING_AGG(distinct case when t3.id = 425 then t2.name end), '') AS name5,
COALESCE(STRING_AGG(distinct case when t3.id = 428 then t2.name end), '') AS name6,
COALESCE(STRING_AGG(distinct case when t3.id = 438 then t2.name end), '') AS name7,
COALESCE(STRING_AGG(distinct case when t3.id = 440 then t2.name end), '') AS name8,
COALESCE(STRING_AGG(distinct case when t3.id = 443 then t2.name end), '') AS name9,
COALESCE(STRING_AGG(distinct case when t3.id = 445 then t2.name end), '') AS name10
FROM
t1 t2
JOIN
t3 ON t2.id = t3.id
WHERE
t3.id = 445;
这个查询会根据id
字段的值将name
字段的值聚合到不同的列中。如果某个id
没有对应的name
值,那么对应的列将为空字符串。
本文来自投稿,不代表新手站长_郑州云淘科技有限公司立场,如若转载,请注明出处:https://www.cnzhanzhang.com/19867.html