PostgreSQL:如何汇总文本,以便在同一行中显示? (通过ID分组)
从一组学生的名字中,我想确定每个ID的学生执行哪个步骤。
这是我得到的输出:
id step1 step2 step3
1 Sam
1 John
2 Ana
2 Charlie
2 Bob
3 Alex
我使用代码获得的输出:
select id,
case when step = 'A' then student_name end as "step1",
case when step = 'B' then student_name end as "step2",
case when step = 'C' then student_name end as "step3"
from my_table
group by id
这是我想获得的输出:
id step1 step2 step3
1 Sam John
2 Ana Charlie Bob
3 Alex
如果名称是数字,我会做:
select id,
sum(case when step = 'A' then student_name end) as "step1",
sum(case when step = 'B' then student_name end) as "step2",
sum(case when step = 'C' then student_name end) as "step3"
from my_table
group by id
但是,这不能用文本执行。如何修改查询以实现上述输出?
From a group of student names, I'd like to identify which student performed which step per id.
This is the output I get:
id step1 step2 step3
1 Sam
1 John
2 Ana
2 Charlie
2 Bob
3 Alex
which I obtain with the code:
select id,
case when step = 'A' then student_name end as "step1",
case when step = 'B' then student_name end as "step2",
case when step = 'C' then student_name end as "step3"
from my_table
group by id
This is the output I'd like to get:
id step1 step2 step3
1 Sam John
2 Ana Charlie Bob
3 Alex
If the names were numbers, I'd do:
select id,
sum(case when step = 'A' then student_name end) as "step1",
sum(case when step = 'B' then student_name end) as "step2",
sum(case when step = 'C' then student_name end) as "step3"
from my_table
group by id
However, this cannot be performed with text. How can I modify the query to achieve the output above?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的数据
只需使用
max
函数your data
just use
max
functiondbfiddle