Pivot with an indefinite amount of distinct values

后端 未结 2 1590
误落风尘
误落风尘 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:19

    Lamak: Here is how I did it with column aliases. The alias is linked to the value from a column in another table that is linked by `aid'.

    DECLARE
        @cols AS NVARCHAR(MAX),
        @colsAlias 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,'')
    
    SELECT @colsAlias = STUFF((SELECT DISTINCT ',' + QUOTENAME(m.aid) + ' AS ' + QUOTENAME(n.aName)  
        FROM m INNER JOIN n ON m.aid = n.aid
        FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
    
    SET @query = 'SELECT s, ' + @colsAlias + ' FROM 
                    (
                    SELECT grade, aid, s
                        FROM m
                    ) x
    
                PIVOT 
                (
                    MIN(grade) FOR aid IN (' + @cols + ')
                ) p '
    
    EXECUTE(@query)
    

提交回复
热议问题