如何将行数据转换为列?

时间:2011-07-13 10:56:24

标签: sql database

我从sql表中获取此数据,但不知道如何将其放入下面的表结构中。将数据转换为该结构的最佳方法是什么?

2011/07/13  Wednesday   10:00   1       
2011/07/13  Wednesday   10:30   1       
2011/07/13  Wednesday   11:00   0   
... 
2011/07/15  Friday      10:00   1       
2011/07/15  Friday      10:30   0       
2011/07/15  Friday      11:00   0       
2011/07/15  Friday      11:30   1   
... 
2011/07/16  Saturday    09:00   0       
2011/07/16  Saturday    09:30   1       
2011/07/16  Saturday    10:00   1   
...       
2011/07/17  Sunday      10:00   1       
2011/07/17  Sunday      10:30   0       
2011/07/17  Sunday      11:00   0       
2011/07/17  Sunday      11:30   1   
...         

enter image description here

2 个答案:

答案 0 :(得分:1)

如果你的RDBMS不支持PIVOT,你可以这样做:

SELECT
  TIME,
  (SELECT FLAG FROM SCHED S WHERE DATE = '7/13/2011' AND TIME = SCHED.TIME) AS [7/13/2011],
  (SELECT FLAG FROM SCHED S WHERE DATE = '7/14/2011' AND TIME = SCHED.TIME) AS [7/14/2011]
  ... other date columns ...
FROM            
   SCHED

这假设您的表具有以下结构:

CREATE TABLE SCHED
(
    [DATE] date,
    TIME char(5),
    FLAG tinyint
)

您可能希望使用日期/时间函数来计算相对于子查询中当前日期的日期,而不是像我一样对它们进行硬编码,但您明白了: - )

答案 1 :(得分:0)

使用pivot运算符(MS-SQL)

见这里:
How to transform a datatable to a ReportingService-like matrix?