多列的SQL动态数据透视表

时间:2016-11-21 18:45:55

标签: sql-server

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

select @cols = STUFF((SELECT ',' + QUOTENAME(Symbol) 
                from Opt 
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'')   
set @query = 'SELECT Date,' + @cols + ' from 
         (
            select Date, Symbol, Price
            from Opt 
        )x
        pivot 
        (
            max(Price)
            for Symbol in (' + @cols + ')
        ) p'

execute(@query);

我从上面的代码中得到了这个:

Symbols(varchar50)       Date     price      quantity
apple              14/11/2016    30       15
banana             14/11/2016    22       20

我需要这样

Date        apple_price  apple_quantity    banana_price  banana_quantity
14/11/2016  30           15                  22          10

从上面的代码我只得到价格

1 个答案:

答案 0 :(得分:2)

只是你原来的一个小小的转折。注意子查询/ Union All。

Declare @SQL varchar(max)
Select  @SQL = Stuff((Select Distinct 
                             ',' + QuoteName(Symbol+'_Price') 
                           + ',' + QuoteName(Symbol+'_Quantity') 
                      From   Opt For XML Path('')),1,1,'')   
Select  @SQL = 'Select Date,' + @SQL + ' 
                From (
                      Select Date,Item=Symbol+''_Price'',Val=Price From Opt
                      Union All
                      Select Date,Item=Symbol+''_Quantity'',Val=Quantity From Opt
                     ) A
                Pivot (max(Val) For Item in (' + @SQL + ') ) p'

Exec(@SQL);

返回

Date         apple_Price    apple_Quantity  banana_Price    banana_Quantity
2016-11-14   30             15              22              20