sql server pivot : group by with dynamic columns

前端 未结 1 423
小蘑菇
小蘑菇 2021-01-15 17:59

I have done a pivot on a table, generating dynamic columns :

DECLARE @cols AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);

select @cols = STUFF((SELECT d         


        
1条回答
  •  离开以前
    2021-01-15 18:59

    DECLARE @cols AS NVARCHAR(MAX);
    DECLARE @query AS NVARCHAR(MAX);
    
    select @cols = STUFF((SELECT distinct ',' +
                            QUOTENAME(Replace(variable,char(CAST(0x0016 as int)),'')) val
                          FROM TABLEDATA
                          ORDER BY val asc
                          FOR XML PATH(''), TYPE
                         ).value('.', 'NVARCHAR(MAX)') 
                            , 1, 1, '');
    
    SELECT @query =
    
    'SELECT
      time,
      country,
      disease,
      ' + @cols + '
    FROM (
        Select
            time,
            country,
            disease,
            variable,
            convert(decimal(10, 2), value) as value
        From
            TABLEDATA
        ) t
    PIVOT 
    (
      Sum(value)
      FOR variable IN( ' + @cols + ' )' +
    ' ) AS p; ';
    
    
    Execute(@query);
    

    Example Fiddle

    0 讨论(0)
提交回复
热议问题