In a simple query the order of your GROUP BY fields makes no difference (ignoring developer legibility) to the final result.
EG: SELECT COUNT(*) FROM People GROUP BY Age, Gender will produce the same results as if the GROUP BY fields were flip-flopped.
Generally speaking, under what condition(s) does this apparent commutative property of the GROUP BY fields break down?
I’m looking for a general rule here (EG: “Any expression containing sub-expressions which depend upon one of the grouped fields”)
I’m having a hard time coming up with an example of where the ordering would matter – but my gut tells me it does in some situation(s).
I think the only time it matters is when using ROLLUP to create subtotals
http://msdn.microsoft.com/en-us/library/ms189305(v=sql.90).aspx
Results from Query 1
2
1
3
6
1
2
3
6
12
(9 row(s) affected)
Results from Query 2
2
1
3
1
2
3
3
3
6
12
(10 row(s) affected)