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 |
slstrozier
Starting Member
1 Post |
Posted - 2012-07-20 : 16:28:14
|
I have a table like so....productId _year amount124 2001 125125 2001 454126 2002 75126 2001 256I use the following function to pivot the columns....SELECT * FROM( SELECT productId,_year,amount FROM Products)tPIVOT (SUM(amount) FOR _yearIN ([2001],[2002])) AS pvtAnd I get the resulting table....productId 2001 2002124 125 NULL125 454 NULL126 256 75How can I do a math function on the resulting table? Id like to get the difference of the values of the columns into a new Column.Like so...productId 2001 2002 Totals124 125 NULL 125125 454 NULL 454126 256 75 181Any help would be greatly appreciated for I have spent an entire day on this. |
|
TG
Master Smack Fu Yak Hacker
6065 Posts |
Posted - 2012-07-20 : 17:10:16
|
untested but shouldn't this do it?SELECT *, [200]-[2002] as totals FROM(SELECT productId,_year,amountFROM Products)tPIVOT (SUM(amount) FOR _yearIN ([2001],[2002])) AS pvtEDIT:of course you would need to isnull or coalesce the NULLs:[2001] - coalesce([2002],0)Be One with the OptimizerTG |
 |
|
yosiasz
Master Smack Fu Yak Hacker
1635 Posts |
Posted - 2012-07-20 : 17:13:44
|
i thought of that too but what if there is a span of years.<><><><><><><><><><><><><><><><><>If you don't have the passion to help people, you have no passion |
 |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2012-07-20 : 22:38:17
|
quote: Originally posted by slstrozier I have a table like so....productId _year amount124 2001 125125 2001 454126 2002 75126 2001 256I use the following function to pivot the columns....SELECT * FROM( SELECT productId,_year,amount FROM Products)tPIVOT (SUM(amount) FOR _yearIN ([2001],[2002])) AS pvtAnd I get the resulting table....productId 2001 2002124 125 NULL125 454 NULL126 256 75How can I do a math function on the resulting table? Id like to get the difference of the values of the columns into a new Column.Like so...productId 2001 2002 Totals124 125 NULL 125125 454 NULL 454126 256 75 181Any help would be greatly appreciated for I have spent an entire day on this.
seehttp://visakhm.blogspot.com/2012/04/display-total-rows-with-pivotting-in-t.html------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
|
|
|
|