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.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Include totals with PIVOT

Author  Topic 

rcampo
Starting Member

2 Posts

Posted - 2007-05-13 : 02:13:51
Hello,
I'm learning this new PIVOT feature in SQL Server 2005 and I might need some help. How can I include a "total" column in the resultset? Here is some data that I'm using:

test_table:
id num_avail color
--- ----------- -------
1 5 Blue
2 2 White
3 2 White

I'm trying to come up with something like this:

AVAILABLE WHITE AVAILABLE BLUE TOTAL AVAILABLE
--------------- -------------- ---------------
4 5 9

but with the PIVOT I only get this:

AVAILABLE WHITE AVAILABLE BLUE
--------------- --------------
4 5

How can I include that last column ('TOTAL AVAILABLE')? I can get it with this:

select [AVAILABLE WHITE] = sum(case when color='White' then num_avail end),
[AVAILABLE BLUE] = sum(case when color='Blue' then num_avail end),
[TOTAL AVAILABLE] = sum(num_avail)
from test_table

but I don't know how to do it using PIVOT (don't even know if it's possible).
Thanks a lot in advance.


chiragkhabaria
Master Smack Fu Yak Hacker

1907 Posts

Posted - 2007-05-13 : 02:36:02
Well your query does work..


Declare @Table Table
(
id int,
num_avail int,
color varchar(10)
)

Insert @Table
Select 1,5,'Blue' Union All
Select 2,2,'White' Union All
Select 3,2,'White'

select [AVAILABLE WHITE] = sum(case when color='White' then num_avail end),
[AVAILABLE BLUE] = sum(case when color='Blue' then num_avail end),
[TOTAL AVAILABLE] = sum(num_avail)
from @Table

--Output

(3 row(s) affected)
AVAILABLE WHITE AVAILABLE BLUE TOTAL AVAILABLE
--------------- -------------- ---------------
4 5 9


Chirag

http://chirikworld.blogspot.com/
Go to Top of Page

rcampo
Starting Member

2 Posts

Posted - 2007-05-13 : 02:49:46
Hi,
Thanks for the quick response. I was trying to use the PIVOT operator in this query:

select [White] as [AVAILABLE WHITE], [Blue] as [AVAILABLE BLUE]
from (select color, num_avail
from test_table) c
pivot (
sum(num_avail)
for color in ([White], [Blue])
) pvt


but I don't know how to include the [TOTAL AVAILABLE] there. I guess I'll have to stick with the "old version" (using CASE statements), which proves to work fine.
Thank you.


Go to Top of Page
   

- Advertisement -