2

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
  • Mind you asking this, whom this is required by? Commented May 26, 2022 at 9:04

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.