Saturday, January 18, 2014

Grouping Sets

Grouping sets and organizing data is something that I still have a hard time with, and from what I've read online it is very rarely used "in the wild".

None the less I know that understanding how to cube, roll up, and group into sets will likely pay dividends when I move into understanding another concept within Tsql.

SELECT s.shipperid, COUNT(*) AS numorders
FROM sales.orders AS s
GROUP BY shipperid

I think that the book does a great job starting with a very simple command then building upon it.  I will post homework as soon as I complete working through book examples/ exercises and reading through the chapter (maybe a few times).

Furthermore, here is a great explanation of grouping sets, I especially like the quoted explanation at the bottom of the page, vhttp://www.adathedev.co.uk/2011/01/grouping-sets-in-sql-server.html

The author gives the following example:

SELECT d.[ProductID], p.ProductCategoryID, SUM(d.LineTotal) AS Total
FROM SalesLT.SalesOrderDetail d
JOIN SalesLT.Product p ON d.ProductID = p.ProductID
GROUP BY GROUPING SETS((d.ProductID),(p.ProductCategoryID), ())

and the quote regarding grouping sets  in the specific code is "Return the totals grouped by ProductId, and also the totals grouped by ProductCategoryID and then also the Grand Total (indicated by the final pair of empty brackets).  

Cheers

No comments:

Post a Comment