0

I have the SQL query which generates a table with users and their answers for the task numbers:

Current result

Which SQL query should I use to get something like this:

Required result

I have 50 question numbers and about 1500 users. Unfortunately, it seems to me that simple SELECT and GROUP BY cannot do here.

Thank you very much!

1
  • Sample data is better presented as formatted text. See here for some tips on how to create nice looking tables. Commented Nov 25, 2020 at 18:43

1 Answer 1

1

You can use conditional aggregation:

select username,
       max(answer) filter (where task_number = 1) as task_1,
       max(answer) filter (where task_number = 2) as task_2
from t
group by username;
Sign up to request clarification or add additional context in comments.

2 Comments

It works! Thank you very much! But, could you explain why we should use max(answers)?
@VladDeryabkin . . . There is only one row that matches the filtering conditions. You need an aggregation function, so max() is as good as any such function.

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.