根据 id 将多行合并为一行
merging multiple rows into one based on id
我在 amazon redshift 数据库中有这种格式的数据:
id
answer
1
house
1
apple
1
moon
1
money
2
123
2
xyz
2
abc
我正在寻找的是:
id
answer
1
house, apple, moon, money
2
123, xyz, abc
有什么想法吗?问题是我不能对答案进行硬编码,因为它们是可变的,所以最好是一个解决方案,它可以简单地为每个 id 的行获取答案并将它们放在一起,用分隔符分隔。
你可以使用聚合函数listagg
:
select id , listagg(answer,',')
from table
group by id
您可以将 string_agg(concat(answer,''),',')
与 group by
一起使用,所以它会像这样:
select id , string_agg(concat(answer,''),',') as answer
from table
group by id
编辑:
你不需要连接,你可以只使用 string_agg(answer,',')
我在 amazon redshift 数据库中有这种格式的数据:
id | answer |
---|---|
1 | house |
1 | apple |
1 | moon |
1 | money |
2 | 123 |
2 | xyz |
2 | abc |
我正在寻找的是:
id | answer |
---|---|
1 | house, apple, moon, money |
2 | 123, xyz, abc |
有什么想法吗?问题是我不能对答案进行硬编码,因为它们是可变的,所以最好是一个解决方案,它可以简单地为每个 id 的行获取答案并将它们放在一起,用分隔符分隔。
你可以使用聚合函数listagg
:
select id , listagg(answer,',')
from table
group by id
您可以将 string_agg(concat(answer,''),',')
与 group by
一起使用,所以它会像这样:
select id , string_agg(concat(answer,''),',') as answer
from table
group by id
编辑:
你不需要连接,你可以只使用 string_agg(answer,',')