Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
actsql
Starting Member
34 Posts |
Posted - 2013-07-31 : 12:28:20
|
I have a table where the designer allowed time reporting for 8 different types of activity on each timecard, then stored the hours by activity in 8 separate columns in the database. Example:Table A.Column Headers: Employee|Date|Phase1Hours|Phase2Hours, etc...Data: Fred Jones| 7/15/13 |3|3, etc...The problem is there is no way based on this structure to get an employee's hours for the day in columnar form.To get this data into columnar form I have used Select queries with Union All, for instance:SELECT Employee, Date, Phase1FROM Table AUNION ALLSELECT Employee, Date, Phase2FROM Table A,etc.....Query is running slow (I am guessing it is because the same table is repeatedly being accessed).Has anyone run into a similar situation and found a faster more efficient solution?Thanks. |
|
James K
Master Smack Fu Yak Hacker
3873 Posts |
Posted - 2013-07-31 : 12:44:10
|
quote: Originally posted by actsql I have a table where the designer allowed time reporting for 8 different types of activity on each timecard, then stored the hours by activity in 8 separate columns in the database. Example:Table A.Column Headers: Employee|Date|Phase1Hours|Phase2Hours, etc...Data: Fred Jones| 7/15/13 |3|3, etc...The problem is there is no way based on this structure to get an employee's hours for the day in columnar form.To get this data into columnar form I have used Select queries with Union All, for instance:SELECT Employee, Date, Phase1FROM Table AUNION ALLSELECT Employee, Date, Phase2FROM Table A,etc.....Query is running slow (I am guessing it is because the same table is repeatedly being accessed).Has anyone run into a similar situation and found a faster more efficient solution?Thanks.
You can try UNPIVOT. The query would be something like this:SELECT Employee,Date,Hourse, Phase FROM TableAUNPIVOT ([Hours] FOR Phase IN ([Phase1Hours],[Phase2Hours],[Phase3Hours]))U; |
|
|
actsql
Starting Member
34 Posts |
Posted - 2013-07-31 : 13:19:37
|
Thank you for the suggestion. I will try it. |
|
|
actsql
Starting Member
34 Posts |
Posted - 2013-07-31 : 13:46:27
|
Worked. Very cool. Thanks much James K! |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2013-08-01 : 03:24:49
|
Also this if sql 2008 or aboveSELECT *FROM(SELECT Employee,Date FROM TableA)tCROSS APPLY (VALUES ('Phase1',[Phase1Hours]),('Phase2',[Phase2Hours]),('Phase3',[Phase3Hours]))t1(Phase,Hours) ------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs |
|
|
|
|
|
|
|