Converting columns to rows
I want to show columns into rows. For example, I have a table, Weekly_Timesheet, with the following structure:
Emp_code
Weekend_Dt
SUN_NT
MON_NT
TUE_NT
WED_NT
THUR_NT
FRI_NT
SAT_NT

I want to list rows on a daily basis. i.e. each day's field, SUN_NT to SAT_NT, for a weekly row converted to daily basis:

Emp_Code
Daily_Dt
NT

    Requires Free Membership to View

    By submitting your registration information to SearchOracle.com you agree to receive email communications from TechTarget and TechTarget partners. We encourage you to read our Privacy Policy which contains important disclosures about how we collect and use your registration and other information. If you reside outside of the United States, by submitting this registration information you consent to having your personal data transferred to and processed in the United States. Your use of SearchOracle.com is governed by our Terms of Use. You may contact us at webmaster@TechTarget.com.

Going from columns to rows is actually a lot easier than going the other way, as in Consolidate data on multiple rows into one (01 August 2003).

The solution for your particular problem requires date arithmetic. Since you did not indicate the database system you're using, I'm going offer a solution using SQL Server syntax. Ordinarily, I would just give standard SQL syntax, but very few database systems, to my knowledge, support standard SQL date arithmetic (which involves INTERVALs or something -- I'm not totally sure). So if you're using a different database system, you'll need a different date function instead of SQL Server's DATEADD().

Also, I'm going to assume your column Weekend_Dt is the date of the Saturday at the end of the week. Therefore, the value SUN_NT is the value for the date that's 6 days earlier, MON_NT for 5 days earlier, etc.

select Emp_code
     , dateadd(dd,-6,Weekend_Dt) as Daily_Dt
     , SUN_NT                    as NT
  from Weekly_Timesheet
union all
select Emp_code
     , dateadd(dd,-5,Weekend_Dt)
     , MON_NT
  from Weekly_Timesheet
union all
select Emp_code
     , dateadd(dd,-4,Weekend_Dt)
     , TUE_NT
  from Weekly_Timesheet
union all
select Emp_code
     , dateadd(dd,-3,Weekend_Dt)
     , WED_NT
  from Weekly_Timesheet
union all
select Emp_code
     , dateadd(dd,-2,Weekend_Dt)
     , THUR_NT
  from Weekly_Timesheet
union all
select Emp_code
     , dateadd(dd,-1,Weekend_Dt)
     , FRI_NT
  from Weekly_Timesheet
union all
select Emp_code
     , Weekend_Dt 
     , SAT_NT
  from Weekly_Timesheet

Note the use of UNION ALL instead of UNION because there's no need to eliminate duplicate rows, since there won't be any, because all the dates are different across the subselects.


This was first published in September 2003

Join the conversationComment

Share
Comments

    Results

    Contribute to the conversation

    All fields are required. Comments will appear at the bottom of the article.