Pivot with an indefinite amount of distinct values

后端 未结 2 1593
误落风尘
误落风尘 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)
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题