How to pivot rows to data with T-SQL?

时间:2019-04-16 23:25:14

标签: sql-server tsql pivot

I have the following data:

code  desc       amt   month
----- ---------- ----- ------
aa    item aa    12    4/2019
aa    item aa    7     5/2019
bb    item bb    5     4/2019
bb    item bb    35    5/2019
bc    widget bc  109   3/2019
bc    widget bc  100   4/2019
df    widget df  29    5/2019

I want to pivot this data so that it looks like this:

code  desc       3/2019   4/2019   5/2019
----- ---------- -------- -------- --------
aa    item aa         0       12        7
bb    item bb         0        5       35
bc    widget bc     109      100        0
df    widget df       0        0       29

All of the pivot examples I see include aggregation functions, but, I don't want to aggregate, I just need to combine/transpose the data. How can I do this?

2 个答案:

答案 0 :(得分:2)

Assuming you want dynamic columns ... then you'll need a little dynamic SQL

Example

Declare @SQL varchar(max) = '
Select *
 From YourTable
 Pivot (sum(amt) For [month] in (' + Stuff((Select Distinct ','+QuoteName(month) 
                                               From YourTable A  
                                               Order By 1 
                                               For XML Path('')),1,1,'')  + ') ) p'
Exec(@SQL);
--Print @SQL

Returns

enter image description here

The Dynamic SQL Looks like this

Select *
 From  YourTable
 Pivot (sum(amt) For [month] in ([3/2019],[4/2019],[5/2019]) ) p

答案 1 :(得分:0)

There is a pivot function you can directly use in T-sql, try this https://docs.microsoft.com/en-us/sql/t-sql/queries/from-using-pivot-and-unpivot?view=sql-server-2017