2012-10-15 52 views
1

我有一个表格,表示Timesheet,它有一个一周的时间条目存储为一行。例如:将列转换为行的SQL查询

ID Start Date Sun Mon Tue Wed Thu Fri Sat 
------------------------------------------------- 
1 14-Oct-2012 0 1 1 2 3 5 0 

开始日期始终是星期日的日期。 我需要根据输入条件将这些数据导出到多个行中,每个日期一行。

例如,如果输入的标准是:日期是10月17日2012年10月15日 - 2012年间,我的输出应该是这样的:

Date Hours 
------------ 
15-Oct 1 
16-Oct 1 
17-Oct 2 

我使用SQL Server 2000中,请给我一个方法。

+4

参见[透视使用SQL Server 2000](http://stackoverflow.com/questions/312861/pivot-using-sql-server-2000) – Spevy

回答

2

SQL Server 2000中,没有一个UNPIVOT功能,使您可以使用UNION ALL来查询这些数据,并得到它的格式要:

select date, hours 
from 
(
    select id, startdate date, sun hours 
    from yourtable 
    union all 
    select id, dateadd(dd, 1, startdate), mon 
    from yourtable 
    union all 
    select id, dateadd(dd, 2, startdate), tue 
    from yourtable 
    union all 
    select id, dateadd(dd, 3, startdate), wed 
    from yourtable 
    union all 
    select id, dateadd(dd, 4, startdate), thu 
    from yourtable 
    union all 
    select id, dateadd(dd, 5, startdate), fri 
    from yourtable 
    union all 
    select id, dateadd(dd, 6, startdate), sat 
    from yourtable 
) x 
where date between '2012-10-15' and '2012-10-17' 

SQL Fiddle With Demo

+0

这工作就像一个魅力!非常感谢! :) – Paramesh

0

这是你可以得到所有列的列表中的表:

SELECT c.colid, c.name 
FROM syscolumns c, sysobjects t 
WHERE c.id = t.id 
AND t.name = <YOUR_TABLE> 
AND t.xtype = 'U' 
ORDER BY c.colid; 

你可以声明,作为一个子查询,并加入到它和输出任何你想要的colums。