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]
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:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(aid)
FROM m
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT s, ' + @cols + ' from
(
select grade, aid, s
from m
) x
pivot
(
sum(grade)
for aid in (' + @cols + ')
) p
ORDER BY p.s'
execute(@query)