PostgreSQL:如何聚合文本以使其显示在同一行中? (按id分组)

PostgreSQL: How to aggregate text so it show in the same row? (grouping by 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

但是,这不能用文本来执行。如何修改查询以实现上述输出?

您的数据

CREATE TABLE mytable(
   id    INTEGER  
  ,step1 VARCHAR(30) 
  ,step2 VARCHAR(30)
  ,step3 VARCHAR(30)
);
INSERT INTO mytable
(id,step1,step2,step3) VALUES 
(1,'Sam',NULL,NULL),
(1,NULL,'John',NULL),
(2,'Ana',NULL,NULL),
(2,NULL,'Charlie',NULL),
(2,NULL,NULL,'Bob'),
(3,NULL,'Alex',NULL);

只需使用max函数

SELECT id,
       Max(step1) step1,
       Max(step2) step2,
       Max(step3) step3
FROM   mytable
GROUP  BY id
ORDER  BY id ASC  

dbfiddle