透视具有多个列和行

时间:2013-03-13 17:15:02

标签: sql pivot unpivot

你能帮助我实现以下目标吗?

我有这个SQL输出表

DateWeek Keep_1 This_1 Order_1 Keep_2 This_2 Order_2 Keep_1-Keep_2 This_1-This_2 Order_1-Order_2
1/1/2013 9      8      7       6       5     4       3             3             3

并将其转换为

RowOrder Column_1 Column_2 Column_1-Column_2
Keep     9        6        3
This     8        5        3
Order    7        4        3

如你所见,我必须保留行中的顺序,所以我不能按字母顺序排序。另外,我必须将Keep_1 This_1 Order_1Keep_2 This_2 Order_2放在一起,并Column_1Column_2一起操作

任何想法如何实现这一目标?

由于

1 个答案:

答案 0 :(得分:1)

如果您使用的是SQL Server 2008+,则可以使用CROSS APPLYVALUES

select c.roworder,
  c.col1,
  c.col2,
  c.col3
from yourtable t
cross apply
(
  values 
    ('Keep', Keep_1, Keep_2, Keep_1_Keep_2),
    ('This', This_1, This_2, This_1_This_2),
    ('Order', Order_1, Order_2, Order_1_Order_2)
) c (roworder, col1, col2, col3)

请参阅SQL Fiddle with Demo

这也可以在任何数据库中使用UNION ALL查询来完成:

select 'Keep' RowOrder, 
  Keep_1 col1, 
  Keep_2 col2, 
  Keep_1_Keep_2 col3
from yourtable
union all
select 'This' RowOrder, 
  This_1 col1, 
  This_2 col2, 
  This_1_This_2 col3
from yourtable
union all
select 'Order' RowOrder, 
  Order_1 col1, 
  Order_2 col2, 
  Order_1_Order_2 col3
from yourtable

请参阅SQL Fiddle with Demo