2016-03-03 61 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);