Using Grouping Sets with Group By Clause Example

Posted on : 04-08-2011 | By : Devi Prasad | In : SQL Server Basics

Share:

0


Grouping Sets is newly introduced in SQL Server 2008.

The use of Grouping Sets is that it simplifies the process of using group by on multiple columns one at a time.

Following are the steps that can be performed using a single Grouping Sets statement:
1) Group by on one column and calculate the result
2) Group by another column and calculate the result
3) Union the the result sets in steps 1 and 2

Following is the generic example for using Grouping Sets:

Let us consider a table @Invoice which contains the sales data with details of the product subproduct and amount. This table has some test data.
[sql]
DECLARE @Invoice TABLE(
Product varchar(50),
Subproduct varchar(50),
Amount int)

INSERT INTO @Invoice
SELECT ‘PEN’,’NIB PEN’,100
UNION
SELECT ‘PEN’,’NIB PEN’,200
UNION
SELECT ‘PEN’,’INK BRUSH’,200
UNION
SELECT ‘PEN’,’QUILL’,250
UNION
SELECT ‘PEN’,’QUILL’,500
UNION
SELECT ‘PEN’,’QUILL’,250
UNION
SELECT ‘PEN’,’REED PEN’,300
UNION
SELECT ‘PENCIL’,’Coloured pencil’,50
UNION
SELECT ‘PENCIL’,’Coloured pencil’,60
UNION
SELECT ‘PENCIL’,’Carbon pencil’,10
UNION
SELECT ‘ERASER’,’gum eraser’,20
UNION
SELECT ‘ERASER’,’gum eraser’,50

[/sql]

With the above table following will be the query to calculate the total sales for each product individually and the total sales for each subproduct individually:

[sql]
SELECT NULL AS Product,Subproduct, COUNT(*) FROM @Invoice
GROUP BY Subproduct
union all
SELECT Product,NULL AS Subproduct, COUNT(*) FROM @Invoice
GROUP BY Product
[/sql]

Output of the above query will be:

Grouping Sets

Grouping Sets

The same result set can be gained by using Grouping Sets as shown in the below query:
[sql]
SELECT Product,Subproduct, COUNT(*) FROM @Invoice
GROUP BY GROUPING SETS(Product,Subproduct)
[/sql]

If the result set has to be grouped by Product and Subproduct, Product, Subproduct
Following would be the union all statement:
[sql]
SELECT Product,Subproduct, COUNT(*) FROM @Invoice
GROUP BY Product,Subproduct
union all
SELECT NULL AS Product,Subproduct, COUNT(*) FROM @Invoice
GROUP BY Subproduct
union all
SELECT Product,NULL AS Subproduct, COUNT(*) FROM @Invoice
GROUP BY Product
[/sql]

This can be achieved simply by using grouping sets as shown below:
[sql]
SELECT Product,Subproduct, COUNT(*) FROM @Invoice
GROUP BY GROUPING SETS((Product,Subproduct),Product,Subproduct)
[/sql]




References : Devi Prasad (sqlserverlearner.com)

Need Help On SQL Server?

Cannot Find Solution to your problem (or) If you are looking for some help on SQL Server. Dont worry Click Here to Post your question and solve your issue.


Do you like my blog?

If you liked reading this blog, please help spread the word by sharing this blog with your friends.




Write a comment



Tags: , ,