I have written this query:
SELECT s, [1] AS a1, [2] AS a2, [3] AS a3, [4] AS a4
FROM (SELECT grade, aid, s FROM m) p
PIVOT
(
SUM(grade)
FOR aid IN ([1], [2], [3], [4])
) AS pvt ORDER BY pvt.s;
That returns the result:
s a1 a2 a3 a4
1 25 69 95 56
2 27 99 16 87
. . . .
99 98 12 34 76
Which is exactly the result I want. My problem is that there will not always be four distinct values in ‘aid’. Is it possible to rewrite this query (or use a stored procedure) so that the amount of ‘a*’ columns depends on how many distinct values are in ‘aid’?
You will need to use a Dynamic Pivot to get the list of columns that you want. This will retrieve the list of columns first and then pivot that list. Something similar to this: