SQL - Group by Grouping Sets examples

I’m trying to get the hang of the ‘Group By Grouping Sets’ syntax, and I’m always having to look it up. Here is a quick little bit of example code that will get you started

GROUPING SETS ( )

Specifies multiple groupings of data in one query. Only the specified groups are aggregated instead of the full set of aggregations that are generated by CUBE or ROLLUP. The results are the equivalent of UNION ALL of the specified groups. GROUPING SETS can contain a single element or a list of elements. GROUPING SETS can specify groupings equivalent to those returned by ROLLUP or CUBE. The <grouping set item list> can contain ROLLUP or CUBE.

( )

The empty group generates a total


--declare a table variable
Declare @myTable table (CustomerID varchar(10), SalesOrder varchar(10), Quantity int, Item varchar(10) )
 
--populate the table
insert into @myTable values ('1234', 'ORD001', 1, 'Hammer'),
                            ('1234', 'ORD001', 1, 'Hammer') ,
                            ('1234', 'ORD002', 1, 'Hammer') ,
                            ('1234', 'ORD002', 1, 'Hammer') ,
                            ('1234', 'ORD003', 1, 'Hammer') ,
                            ('9999', 'ORD004', 1, 'Hammer') ,
                            ('9999', 'ORD004', 1, 'Hammer') ,
                            ('9999', 'ORD005', 1, 'Hammer') ,
                            ('9999', 'ORD006', 1, 'Hammer') ,
                            ('9999', 'ORD006', 1, 'Hammer')
 
--first a regular select statement to see that it all looks good
Select * from @myTable
 
--finally a GROUPING SETS example
--not that we put the text 'TOTAL' in the places that would have been 'NULL',
--this has the effect of sorting the totals to the bottom
select isnull(customerid,'TOTAL') as CustomerID, isnull(SalesOrder,'TOTAL') as SalesOrder, COUNT(1) as linecount
    from @myTable
    group by grouping sets ( (CustomerID, SalesOrder),(CustomerID),() )
    order by 1,2,3

RealWorldCode gives developers practical, real‑world solutions with clean, working code — no fluff, no theory, just answers.
Links
Home
Knowledge Areas
Sitemap
Contact
Et cetera
Privacy Policy
Terms and Conditions
Cookie Preferences