2016-03-03 17 views
0

說我有一個看起來像這樣的數據線:SQL Calcluated字段轉換數據的行成基於列的多個值

[Customer] - [$ spent of shirts] - [$ spent on pants] - [$ spent on shoes] 
John - $10 - $20 - $15 
Maria - $20 - $10 - $50 

但我想改變一下這樣的數據:

[Customer] - [Product] - [Amount Spent] 
John - Shirts - $10 
John - Pants - $20 
John - Shoes - $15 
Maria - Shirts - $20 
Maria - Pants - $10 
Maria - Shoes - $50 

這可能嗎?是否有計算出的邏輯可以使用頂級數據行爲產品和金額花費創建?

謝謝!

+1

您正在尋找Unpivoting表,徵求這裏,有噸的就可以了提問。 –

+0

我刪除了mysql標籤,因爲列標題提示SQL Server。 –

回答

0

我想做到這一點使用cross apply

select v.* 
from t cross apply 
    (values ([Customer], 'Shirts', [$ spent of shirts]), 
      ([Customer], 'Pants', [$ spent of pants]), 
      ([Customer], 'Shoes', [$ spent of shoes]) 
    ) v(Customer, Product, AmountSpent);