SQL组列出每个名称的所有值

时间:2017-09-25 18:25:39

标签: sql postgresql

我试图让这个不要重复学生的名字。我是SQL查询的新手。只是想知道是否有一个更好的方法来做到这一点,让每个学生都列在一行中。

column-gap

给了我

SELECT s.name students, c.name classes 
FROM students s  INNER JOIN enrollments e ON s.id=e.student_id 
INNER JOIN classes c ON e.class_id=c.id 
GROUP BY s.name, c.name;

好奇是否有更清洁的方式。

2 个答案:

答案 0 :(得分:3)

也许你想要listagg()

SELECT s.name as students, listagg(c.name) within group(order by c.name) as classes 
FROM students s INNER JOIN
     enrollments e
     ON s.id = e.student_id INNER JOIN
     classes c
     ON e.class_id = c.id 
GROUP BY s.name, c.name;

这将创建一个逗号分隔的每个学生所在班级的列表。

编辑:

在Postgres中,您可以使用string_agg()

SELECT s.name as students, string_agg(c.name order by c.name) as classes 
FROM students s INNER JOIN
     enrollments e
     ON s.id = e.student_id INNER JOIN
     classes c
     ON e.class_id = c.id 
GROUP BY s.name, c.name;

答案 1 :(得分:1)

非常感谢menuItem.enabled = false; !他对@Jacob H的建议就像一个魅力。

string_agg

导致......

SELECT s.name students, string_agg(c.name, '|') classes 
FROM students s  INNER JOIN enrollments e ON s.id=e.student_id 
INNER JOIN classes c ON e.class_id=c.id 
GROUP BY s.name;