Pivot with an indefinite amount of distinct values

后端 未结 2 1594
误落风尘
误落风尘 2021-02-04 13:29

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]         


        
2条回答
  •  一整个雨季
    2021-02-04 14:28

    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)
    

提交回复
热议问题