SQL Calcluated字段根据列值将数据行转换为多行

时间:2016-03-03 19:29:15

标签: sql sql-server sql-server-2008

说我的数据行看起来像这样:

[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 

这可能吗?我是否可以使用顶部数据线为Product和Amount Spent创建计算逻辑?

谢谢!

1 个答案:

答案 0 :(得分: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);