Mar
3
Written by:
Steve Gray
3/3/2011 1:28 PM
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, written against the AdventureWorks DB
Code Snippet
- select h.CustomerID, h.SalesOrderNumber, COUNT(1) as linecount
- from sales.SalesOrderHeader h
- join sales.SalesOrderDetail d on h.SalesOrderID = d.SalesOrderID
- where h.CustomerID in (1,2)
- group by grouping sets ( (h.CustomerID, h.SalesOrderNumber),(h.CustomerID),() )
- order by 1,2,3
This will give us this result set:

As always, I welcome your comments!