Alias names to with rollup in SQL queries?

vision picture vision · Sep 19, 2013 · Viewed 18.4k times · Source

I am using with rollup in my sql query. I am not getting alias name for rollup.

My SQL is

SELECT [Column1],
       sum([Column2])
FROM   Tablea
GROUP  BY [Column2] WITH ROLLUP 

Which returns

s       8
t       8
j       8
null    24 

How can I replace the NULL in the total row?

Answer

Martin Smith picture Martin Smith · Sep 19, 2013

You can use the GROUPING function in a CASE expression.

SELECT CASE
         WHEN GROUPING([Column1]) = 1 THEN 'Total'
         ELSE [Column1]
       END [Column1],
       sum([Column2])
FROM   Tablea
GROUP  BY [Column1] WITH ROLLUP 

SQL Fiddle