PostgreSQL : Aggregate multiple rows from a table into a single record

Viewed 97

I need to aggregate multiple rows in a table into a single record using an SQL query. Below is the table structure and the required output details,

enter image description here

enter image description here

1 Answers

This is a basic pivot query requirement. On Postgres, we can try:

SELECT id, name,
       'english' AS subject1,
       MAX(marks) FILTER (WHERE subject = 'english') AS marks1,
       'math' AS subject2,
       MAX(marks) FILTER (WHERE subject = 'math') AS marks2,
       'science' AS subject3,
       MAX(marks) FILTER (WHERE subject = 'science') AS marks3
FROM yourTable
GROUP BY id, name;

screen capture from demo link below

Demo

Related