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
 General SQL Server Forums
 New to SQL Server Programming
 how to use rollup in a query with pivot clause

Author  Topic 

learning_grsql
Posting Yak Master

230 Posts

Posted - 2012-08-20 : 16:18:06
HI,

I have used a pivot query but I'm not sure how to use rollup in the query to get the total at the bottom of the results.

Table is similar to below.

date | product | organisation | price
1 july 2012 | biscuitA | xyz | 33
1 july 2012 | icecreamA | abc | 45
1 july 2012 | biscuitB | abc | 22
1 july 2012 | biscuitA | def | 33
1 july 2012 | biscuitB | xyz | 22
2 july 2012 | biscuitA | def | 33
2 july 2012 | icecreamA | xyz | 45
2 july 2012 | icecreamA | abc | 45
2 july 2012 | biscuitB | abc | 22
3 july 2012 | biscuitA | def | 33
3 july 2012 | icecreamA | xyz | 45
3 july 2012 | biscuitA | xyz | 33


My code is below.


select product, [xyz] as xyz, [abc] as abc, [def] as def, sum([xyz] + [abc] + [def] as Total
from
(
select date, product, price, organisation from table1
) as t
pivot
(
sum(price) for organisation in ([xyz], [abc], [def])
)
as newquery
group by product, abc, xyz, def

The query works fine but now I want to display total at the bottom of the results. I tried 'with rollup' in the last line of my code after group by but it does not produce result as I wanted.

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-08-20 : 16:52:26
see

http://visakhm.blogspot.com/2012/04/display-total-rows-with-pivotting-in-t.html

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

learning_grsql
Posting Yak Master

230 Posts

Posted - 2012-08-20 : 17:28:04
Many thanks Visakh16 as usual. I just followed your blog and edited my code. It works now.

But I have a concern here why if I add "with rollup" after group by at the last line (as in my case) in pivot clause don't work. I just like to know the logic if possible. Thanks.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-08-20 : 17:36:18
quote:
Originally posted by learning_grsql

Many thanks Visakh16 as usual. I just followed your blog and edited my code. It works now.

But I have a concern here why if I add "with rollup" after group by at the last line (as in my case) in pivot clause don't work. I just like to know the logic if possible. Thanks.



rollup will cause mutiple total rows to be added based on number of columns involved in group by
if you just need a grandtotal you dont need to use rolup

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -