Search code examples
sqlsql-server-2000

SQL Query to convert columns to rows


I have a table say Timesheet, which is having one week hour entry stored as a row. Eg:

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

The start date is always Sunday's date. I need to export this data into multiple rows, one row for each date, based on input criteria.

For example, if the input criteria is: Date is between 15-Oct-2012 to 17-Oct-2012, my output should be something like:

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

I am using SQL Server 2000, please suggest me a way.


Solution

  • SQL Server 2000, does not have an UNPIVOT function so you can use a UNION ALL to query this data and get it in the format that you want:

    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'
    

    See SQL Fiddle With Demo