How to get the summary on total by using Group with Rollup in SQL Server

No.of Views1365
Bookmarked0 times
Downloads 
Votes0
By  youngmurukan   On  15 Feb 2010 21:02:15
Tag : Sql Servers , T-SQL
How to get the summary on total by using Group with Rollup in SQL Server
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction


In Microsoft SQL Server normally when you use aggregation function you must use Group By clause to get the Total/Average So on. But by using Group by you can get the aggregation only (Total/Avg...etc) based on the columns which you are giving in Group By clause.

But if you want get the subtotals; you can use rollup clause with Group By clause.

Rollup clause would give the subtotal specified columns whatever you mentioned in group by clause.

In the shown example, I need to get the total and subtotal of NoofBooks based on BCode and NoofLeaves but I can only get total based on those columns if I use Group By clause only. For that I can use rollup clause with Group By clause.

When we use rollup clause it would give total of NoofBooks for each BCode and NoofLeaves, subtotal for each BCode and Grand Total of NoOfBooks

Here you can notice that when its give the subtotal for each BCode, NoofLeaves columns filled NULL values as it does not have any values to return. But we can avoid showing as NULL.

The SQL Query for this,

{codecitation class="brush: sql; gutter: true;" width="500px"}

select BCode, NoofLeaves,SUM(NoofBooks) TTL_Books

from ChequeDetails

where jobno='1214200644619 '

group by BCode,NoofLeaves

with rollup

order by BCode,NoofLeaves

{/codecitation}

You can replace the NULL values with your own Text. For that you will have to use the Grouping() function.

Screen

{codecitation class="brush: sql; gutter: true;" width="500px"}

select Case Grouping(BCode)

When 1 Then 'All BCode'

Else BCode

End As BCode ,

Case Grouping(NoofLeaves)

When 1 Then 111

Else NoofLeaves

End As NoofLeaves,SUM(NoofBooks) TTL_Books

from ChequeDetails

where jobno='1214200644619 '

group by BCode,NoofLeaves

with rollup

order by BCode,NoofLeaves

{/codecitation}

Thank you

Mukuran

 
Sign Up to vote for this article
 
About Author
 
youngmurukan
Occupation-Not Provided
Company-Not Provided
Member Type-Senior
Location-Not Provided
Joined date-12 May 2009
Home Page-Not Provided
Blog Page-Not Provided
 
 
Other popularSectionarticles
Comments
By:SunnyDate Of Posted:7/26/2010 4:25:43 PM
Mr.
What to do to show the subtotal below the rows instead of showing on the top
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top