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 |
Pavlo01
Starting Member
6 Posts |
Posted - 2013-05-30 : 18:08:01
|
Can someone help me please!I was asked to query table 1 to look like table 2 using SQLTable 1Cat# CatDesc Year Period_01 Period_02 Period_03 Period_0403 Standard IC 2013 7890 4450 1010 243004 Engnring IC 2013 280 74321 8362 222403Table 2Cat# CatDesc Year Period Amount03 Standard IC 2013 01 789003 Standard IC 2013 02 445003 Standard IC 2013 03 101003 Standard IC 2013 04 243004 Engnring IC 2013 01 28004 Engnring IC 2013 02 7432104 Engnring IC 2013 03 836204 Engnring IC 2013 04 222403 |
|
James K
Master Smack Fu Yak Hacker
3873 Posts |
Posted - 2013-05-30 : 18:16:12
|
You can use the UNPIVOT operator like shown belowSELECT *FROM ( SELECT [Cat#] , CatDesc , Year , Period_01 AS [01] , Period_02 AS [02] , Period_03 AS [03] , Period_04 AS [04] FROM Table1 ) s UNPIVOT( Amount FOR Period IN ( [01], [02], [03] ) ) U |
 |
|
Pavlo01
Starting Member
6 Posts |
Posted - 2013-05-30 : 19:13:35
|
Thank You So Much You've Been A Great HelpLast question, what would the query be if I wanted to do the reverse, from table 2 to table 1. |
 |
|
MuMu88
Aged Yak Warrior
549 Posts |
Posted - 2013-05-30 : 20:05:16
|
Use PIVOT Operation:[CODE]SELECT [Cat#], CatDesc, Year, [01] as Period_01, [02] as Period_02, [03] as Period_03, [04] as Period_04 FROM (SELECT [Cat#], CatDesc, Year, Amount, Period FROM @TEMP2) AS D PIVOT(SUM(Amount) FOR Period IN([01], [02], [03], [04])) AS P;[/CODE] |
 |
|
Pavlo01
Starting Member
6 Posts |
Posted - 2013-05-31 : 03:43:05
|
Can you explain to me how hte pivot and unpivot functions work.Why is there a sum() in Pivot and not in Unpivot. |
 |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2013-05-31 : 03:50:21
|
Pivot is a aggregate operation as you're effectively trying to convert a row value to a column. Hence you need to use an aggregate function like SUM,MAX,AVG etcUnpivot does the opposite. It converts column values from row onto multiple row values based on the column heading------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs |
 |
|
|
|
|
|
|