(微軟官方解釋)FROM - Using PIVOT and UNPIVOTspa
https://msdn.microsoft.com/en-us/library/ms177410.aspxcode
一、PIVOT列值轉置爲行blog
列名爲已知值(靜態列):io
create table table1 ( fcompany nvarchar(20) ,fweek nvarchar(20) ,fvalue int ) insert into table1(fcompany,fweek,fvalue) select 'c1', 'w1',1 union all select 'c1', 'w2',2 union all select 'c1', 'w3',3 union all select 'c1', 'w4',4 union all select 'c1', 'w5',5 union all select 'c1', 'w6',6 union all select 'c1', 'w7',7 insert into table1(fcompany,fweek,fvalue) select 'c1', 'w1',2 union all select 'c1', 'w2',1 union all select 'c1', 'w3',0 union all select 'c1', 'w4',1 union all select 'c1', 'w5',2 union all select 'c1', 'w6',3 union all select 'c1', 'w7',4 insert into table1(fcompany,fweek,fvalue) select 'c2', 'w1',7 union all select 'c2', 'w2',6 union all select 'c2', 'w3',5 union all select 'c2', 'w4',4 union all select 'c2', 'w5',3 union all select 'c2', 'w6',2 union all select 'c2', 'w7',1 select fcompany,w1,w2,w3,w4,w5,w6,w7 from table1 pivot (sum(fvalue) for fweek in (w1,w2,w3,w4,w5,w6,w7)) a
列名爲未知值(動態列):table
DECLARE @SQL NVARCHAR(MAX) DECLARE @SQL1 NVARCHAR(MAX) DECLARE @SQL2 NVARCHAR(MAX) --SELECT 後面的列,null轉爲0 SELECT @SQL1=ISNULL(@SQL1+',','')+'ISNULL(['+AB+'],0) AS '+QUOTENAME(AB) FROM #TEMP_AB01 GROUP BY AB ORDER BY AB --IN 後面的列,要轉置爲行的列值 select @SQL2=ISNULL(@SQL2+',','')+QUOTENAME(AB) FROM #TEMP_AB01 GROUP BY AB ORDER BY AB SET @SQL=N'SELECT A.COMPANY AS [公司],A.[CREATEDATE] AS [建立日期],A.DOCTYPE [交易性質],' + @SQL1 + N' ,TTL_AB AS [異常彙總],TTL_NORMAL AS [正常彙總],TTL_ALL AS [單據總計] ' + ' FROM #TEMP_AB01 PIVOT (SUM(DOC_NUM) FOR AB IN ('+ @SQL2 +')) A ' + ' ,#TEMP_AB02 B ' + ' WHERE A.COMPANY=B.COMPANY AND A.CREATEDATE=B.CREATEDATE AND A.DOCTYPE=B.DOCTYPE ' + ' ORDER BY 1,2,3 ' EXEC(@SQL)
二、UNPIVOT 行轉置爲列class
--1日~31日轉換爲行顯示 select left(YearMonth,4)+'-'+right(YearMonth,2)+'-'+right(dt,2) dt,b.hcode,c.name from dbo.Schedule unpivot (hcode for dt in (D01,D02,D03,D04,D05,D06,D07,D08,D09,D10,D11, D12,D13,D14,D15,D16,D17,D18,D19,D20,D21,D22,D23,D24,D25,D26,D27,D28,D29,D30,D31 )) b,dbo.HolidayCode c WHERE b.hcode=c.hcode and EmpID='1001' and Left(YearMonth,4)='2017' and Right(YearMonth,2)='01' order by 1,2