[英]T-SQL : convert columns to rows
Pivot 逆軸
SELECT CustomerID,PROD1,PROD2,[MONTH] FROM (
SELECT * FROM Input_Table
UNPIVOT(
NUM FOR [MONTH] IN (JUL,AUG,SEP)
)UP ) UP
PIVOT(
MAX(NUM) FOR ProductID IN ([PROD1],[PROD2])
) P
實現這一目標的另一種方法
;with Data as
(
select * from
(
values (1234, 100, 400, 700, 'PROD1')
, (1234, 200, 500, 800, 'PROD2')
, (2345, 300, 600, 900, 'PROD1')
) DataSet (CustomerID, JUL, AUG , SEP, ProductID)
), CustomerData as
(
select CustomerID
, M.[Month]
, M.Val
, D.ProductID
from Data D
cross apply
(
values ('JUL', D.JUL)
, ('AUG', D.AUG)
, ('SEP', D.SEP)
) M ([Month], Val)
)
select CustomerID
, max(case when ProductID = 'PROD1' then Val end) [PROD1]
, max(case when ProductID = 'PROD2' then Val end) [PROD1]
, [Month]
from CustomerData
group by CustomerID, [Month]
order by charindex([Month], 'JUL AUG SEP')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.