Search code examples
sqlsql-servergroup-bysql-order-byrollup

ORDER BY without Total in SQL


I have this SQL query, which uses ROLLUP to get the total but also needs to order every other row by the amount:

SELECT 
    ISNULL([SharepointId], 'Total') as 'Sharepoint', 
    Count([Id]) as 'Nombre de tickets' 
FROM [dbo].[Tickets]
GROUP BY ROLLUP([SharepointId])
ORDER BY 2 DESC, 1

Is there a way to make sure the total stays at the end of the results while keeping the descending order of the other rows?

For now, this is what I get:

Sharepoint         Nombre de tickets
------------------ -----------------
Total              20326
INTERNE            9396
MAIN               1503
...

Solution

  • Other answers are mis-representing what you want.

    • You don't want a row to be last because it's NULL
    • You want a row to be last because it's been grouped


    SQL Server has a function for exactly that, and the docs page has almost exactly your example in it...


    SELECT 
        ISNULL([SharepointId], 'Total') as 'Sharepoint', 
        Count([Id]) as 'Nombre de tickets' 
    FROM [dbo].[Tickets]
    GROUP BY ROLLUP([SharepointId])
    ORDER BY GROUPING([SharepointId]), 2 DESC
    

    GROUPING([SharepointId]) is 0 when the column is not grouped (so those rows sort first) and then it's 1 when the column is grouped (so that row goes last). This is especially useful when rolling up multiple columns.