November 06, 2010

Count SubTotals and Totals using ROLLUP in SQL Server




The SQL Server ROLLUP operator is useful in generating reports that contain subtotals and totals.

Here’s how to use the ROLLUP operator in the Northwind database to give a breakdown of the Orders placed by each Customer as well as the Total number of Orders placed

SELECT ISNULL(CustomerId, 'Total') Customer,
Count(OrderId) as OrdersPlaced
FROM Orders
GROUP BY CustomerId
WITH ROLLUP

OUTPUT

image

Note: If you are using SQL Server 2008, take a look at GROUPING SETS

The same query in SQL Server 2008 can be re-written as

SELECT ISNULL(CustomerId, 'Total') Customer,
Count(OrderId) as OrdersPlaced
FROM Orders
GROUP BY Grouping Sets(CustomerId, ())


Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

 
  Feedback:

comments

0 Responses to "Count SubTotals and Totals using ROLLUP in SQL Server"
 

Copyright © 2009-2014 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions