如何使用sql pivot将行创建到列

时间:2017-04-06 03:25:47

标签: sql sql-server

如何使灵活的枢轴引用以下数据:

当前记录

Year    Month   Week    Sales      Role
2017      1      1      1,000.00    SM
2017      1      1      1,000.00    PS
2017      1      2      1,001.00    PS    
2017      1      3      1,002.00    PS 
2017      1      4      1,003.00    PS 
2017      2      1      1,004.00    PS 
2017      2      2      1,005.00    PS 
2017      2      3      1,006.00    PS 
2017      2      4      1,007.00    PS

欲望输出

Year  Role     1-1       1-2       1-3       1-4      2-1       2-2       2-3       2-4          
2017   PS   1,000.00  1,001.00  1,002.00  1,003.00  1,004.00  1,005.00  1,006.00  1,007.00
2017   SM   1,000.00  

目前我正在使用MSSQL Server 2016.希望得到您的积极回应。

1 个答案:

答案 0 :(得分:0)

Dynamic Pivots的许多例子,但这里是一个快速的答案。

您可能会注意到Order by cast(replace(Col,'-','.') as money)。这是为了确保列的正确顺序(不是1,10,11,2,3)

动态SQL

Declare @SQL varchar(max) = Stuff((Select ',' + QuoteName(Col) 
                                    From (
                                          Select Distinct Col=Concat(Month,'-',Week) From #YourTable 
                                         ) A
                                    Order by cast(replace(Col,'-','.') as money)
                                    For XML Path('')),1,1,'') 

Select  @SQL = '
Select [YAxis1] as [Year],[YAxis2] as [Role],' + @SQL  + '
From (
        Select YAxis1 = Year
              ,YAxis2 = Role
              ,XAxis  = Concat(Month,''-'',Week)
              ,Value  = Sales
         From  #YourTable
     ) A
 Pivot (sum(Value) For [XAxis] in (' + @SQL + ') ) p'
--Print  @SQL
Exec(@SQL);

<强>返回

enter image description here

使用示例数据

Create Table #YourTable  (Year int,Month int,Week int,Sales decimal(10,2), Role varchar(25))
Insert Into #YourTable values
(2017,1,1,1000.00,'SM'),
(2017,1,1,1000.00,'PS'),
(2017,1,2,1001.00,'PS'), 
(2017,1,3,1002.00,'PS'), 
(2017,1,4,1003.00,'PS'), 
(2017,2,1,1004.00,'PS'), 
(2017,2,2,1005.00,'PS'), 
(2017,2,3,1006.00,'PS'), 
(2017,2,4,1007.00,'PS')