I have the table
id year quarter total
1 2016 1 100
1 2016 2 200
1 2016 3 300
1 2016 4 400
2 2016 1 100
2 2016 2 200
I want to get the output:
id year total1 total2 total3 total4
1 2016 100 200 300 400
2 2016 100 200
I have tried
SELECT year,
"1" AS total1,
"2" AS total2,
"3" AS total3,
"4" AS total4
FROM (SELECT
*
FROM mytable
PIVOT (... FOR quarter IN (1, 2, 3, 4))
where year=2016) a
;
PIVOToperator? It's not the way I'd go (I'd use conditional aggregation like the posted answers), but if you have to usePIVOT, you have to usePIVOT.max(total)orsum(total)instead of dots. Pivot needs aggregation, but in this case it will create rows for eachid. The question is what to do if there are two rows for same quarter with same ID. You want sum, max or separate rows?