SQL GROUP BY techniques
I came across this post on the web and thought it useful to duplicate on my blog. The original post can be found here. ======================================================================= One aspect of the versatile SELECT statement that seems to confuse many people is the GROUP BY clause. It is very important to group your rows in the proper place. Always push GROUP BY aggregations as far into your nested SELECT statements as possible – if you have a situation in which you are grouping by long lists of columns that are not part of primary keys, you are probably have not structured your query correctly. Here's a classic example that returns total sales per customer, in addition to returning the customer's name and address: SELECT C.CustomerID, C.CustomerName, C.CustomerType, C.Address1, C.City, C.State, SUM(S.Sales) as TotalSales FROM Customers C INNER JOIN Sales S ON C.CustomerID = S.CustomerID GROUP BY ...