Search code examples
sqlt-sqlgroup-byrollup

How to sort NULL values last - for grouping summary rows with "group by rollup/cube"


When using GROUP BY ... WITH ROLLUP, subtotal/total rows are indicated by NULL values in the grouped columns. That's a nice feature, however I would expect the totals under the detail values, but NULLs are sorted at the beginning.

Example:

SELECT Year, Quarter, SUM(Amount) AS Amount
FROM Table
GROUP BY Year, Quarter WITH ROLLUP
ORDER BY Year, Quarter

Year|Quarter|Amount            Year|Quarter|Amount
----|-------|------    --->    ----|-------|------
NULL|   NULL|   120            1999|      1|    10
1999|   NULL|    40            1999|      2|    10
1999|      1|    10            1999|      3|    10
1999|      2|    10            1999|      4|    10
1999|      3|    10            1999|   NULL|    40
1999|      4|    10            2000|      1|    20
2000|   NULL|    80            2000|      2|    20
2000|      1|    20            2000|      3|    20
2000|      2|    20            2000|      4|    20
2000|      3|    20            2000|   NULL|    80
2000|      4|    20            NULL|   NULL|   120

How to get them at the end?

I know I could replace the NULL values by something which would be sorted where expected, possibly in some other column, but that's a bad workaround.


Solution

  • Just change

    ORDER BY Year, Quarter
    

    to

    ORDER BY GROUPING(Year), Year, GROUPING(Quarter), Quarter
    

    Explanation: this function returns 1 for total rows and 0 for all others.