Poor Man’s SQL Pivot. List Questions as Columns and Answers per User in one row

The posted answers work but are clumsy and slow. You can do what I call parallel aggregation:

SELECT
     ID,
     SUM(case when question_id = 1 then 1 else 0 end) as sum1,
     SUM(case when question_id = 2 then 1 else 0 end) as sum2,
     SUM(case when question_id = 3 then 1 else 0 end) as sum3
GROUP BY ID

This will do one pass over the table instead of three and is very short. It is not a complete walk-through but you can surely adapt the concept to your needs.

Leave a Comment