簡體   English   中英

T-SQL:將列轉換為行

[英]T-SQL : convert columns to rows

輸入表:

在此處輸入圖像描述

所需的 output:

在此處輸入圖像描述

這可以通過單個查詢或創建中間表來實現嗎?

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM