SQL Developer Dont's (Part 2) - The Correct Way to GROUP BY

SUMMARY: Never use fields in the GROUP BY that aren't part of the grouping.  Read on...

I don't know how many times I have seen the following SQL, but it's not always accurate, and most irritating of all it is just wrong.

SELECT C.CustomerID, CustomerName, City, State, Sum(Sales) as TotalSales
FROM Customers C
INNER JOIN Sales S on C.CustomerID = Sales.CustomerID
GROUP BY CustomerID, CustomerName, City, State

The reason developers write a query like this in the first place is they see the common error message that says, "Column X is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause."  The only way they know how to solve this problem is to start adding columns to the the GROUP BY until the query runs.  This is where having an understanding of Set Theory comes in handy.

The query should be written thusly:

SELECT C.CustomerID, C.CustomerName, C.City, C.State, S.TotalSales
FROM Customers C
INNER JOIN
(SELECT CustomerID, SUM(Sales) as TotalSales
FROM Sales 
GROUP BY CustomerID) S
ON C.CustomerID = S.CustomerID

Essentially what this does is it gets the TotalSales from the sales table (that explicity all I want and need to get the total sales).  Then in order to pick up the other data that I need to produce my report, I join on the key field for CustomerID.  Not only is this always going to be correct, it is also the correct way to do the GROUP BY.

Print | posted on Sunday, March 11, 2007 2:08 AM

This article is part of the GWB Archives. Original Author: Brian Sherwin

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.