如何在不使用数据透视表的情况下将行转换或转置为 SQL 中的列?

How to convert or transpose rows to columns in SQL without using pivot?

我在 SQL 中转置数据时遇到了一个问题。例如下面给出的 table

id source_name 价值
1 cp x
1 cp y
1 一个
2 b
2 cp c
2 d
3 e

我需要以下格式的 table(转置但带有字符串聚合)-

id cp
1 x,y 一个
2 c b,d
3 d

使用当前的 sql 查询,我得到以下格式的 table。

id cp
1 x 一个
2 c b
3 d

任何人都可以在 SQL(平台 - Bigquery)中调整查询或建议新查询吗?

当前查询 -

select id, any_value(if(source_name = 'cp', value, null)) as cp,
any_value(if(source_name = 'hi', value, null)) as hi,
any_value(if(source_name = 'li', value, null)) as li
any_value(if(source_name = 'mi', value, null)) as mi
from table_name group by id

尝试 STRING_AGG 而不是 any_value:

select id, string_agg(if(source_name = 'cp', value, null)) as cp,
string_agg(if(source_name = 'hi', value, null)) as hi,
string_agg(if(source_name = 'li', value, null)) as li
string_agg(if(source_name = 'mi', value, null)) as mi
from table_name group by id

改用PIVOT operator

select *
from `project.dataset.table`
pivot (string_agg(value) for source_name in ('cp', 'hi', 'li', 'mi'))    

如果应用于您问题中的样本数据

输出是

如果您想让它动态地为您构建列列表,请查看