John Ryan Camatog
John Ryan Camatog

Reputation: 65

PostgreSQL - JOIN on string_agg

I have three tables.

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

I would like to result to be like this:

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

My current query is:

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;

Is there something wrong with my query? Am I missing something? The error says that student_id needs to be in a GROUP BY clause but I don't want that.

Upvotes: 5

Views: 3705

Answers (1)

Patrick
Patrick

Reputation: 32161

You can do this with a sub-query:

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);

Why exactly do you not want to GROUP BY student_id?

Upvotes: 5

Related Questions