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
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, ())
No comments:
Post a Comment