I want to show columns into rows. For example, I have a table, Weekly_Timesheet, with the following structure:
By submitting your personal information, you agree that TechTarget and its partners may contact you regarding relevant content, products and special offers.
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
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.
Dig Deeper on Oracle and SQL
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.