PostgreSQL - 在string_agg上加入

时间:2015-10-16 03:26:58

标签: postgresql string-aggregation

标题可能会产生误导,因为我似乎无法找到它的权利。但是它就在这里。

我有三张桌子。

Students
student_id | name
1            Rhon

Subjects
subject_id | subject_name | student_id
1            Physics        1
2            Math           1

Grades
grade_id | student_id | subject_id | grade
1          1            1            90
2          1            2            89
3          1            2            88

我想结果如下:

student_id | student_name | subject_name | grades
1            Rhon           Physics        90
1            Rhon           Math           88,89

我目前的查询是:

SELECT students.student_id, subjects.subject_id, string_agg(grades.grade, ',')
FROM students
JOIN subjects ON students.student_id = subjects.student_id
JOIN grades ON subjects.subject_id = grades.subject_id;

我的查询有问题吗?我错过了什么吗?错误说student_id需要在GROUP BY子句中,但我不想这样做。谢谢你提前。

1 个答案:

答案 0 :(得分:2)

您可以使用子查询执行此操作:

SELECT s.student_id, s.student_name, j.subject_name, g.grades
FROM students s
JOIN subjects j
JOIN (
  SELECT student_id, subject_id, string_agg(grade, ',') AS grades
  FROM grades
  GROUP BY student_id, subject_id) g USING (student_id, subject_id);

为什么你不想GROUP BY student_id