--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