将工作日的数据转换为列

时间:2014-07-16 11:34:55

标签: sql-server

我的查询以行格式返回每周的每一天的数据,但我需要以列格式获取它。实现这一目标的最佳方法是什么?

原始数据是:

Sunday | Monday | Tuesday | Wednesday | Thursday | Friday | Saturday <br/>
10       15       18        20          25         18       21

我需要将其转换为

Sunday   | 10
Monday   | 15
Tuesday  | 18
Wednesday| 20
Thursday | 25
Friday   | 18
Saturday | 21

2 个答案:

答案 0 :(得分:1)

您可以在此处使用UNPIVOT关键字,如下所示:

select colname,value from
yourtable
unpivot
(
 value
 for colname in (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday)
) as u
order by colname

SQL Fiddle

答案 1 :(得分:0)

Try this:

SELECT ColNames,Data 
    FROM   YourTable 
           CROSS APPLY ( VALUES ('Sunday', Sunday), 
                                ('Monday ', Monday ), 
                                ('Tuesday ', Tuesday ), 
                                ('Wednesday', Wednesday),
                                ('Thursday ', Thursday ),
                                ('Friday', Friday),
                                ('Saturday ', Saturday ),
    ) V(ColNames, Data)