17

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?

Martin Smith
  • 438,706
  • 87
  • 741
  • 845
vision
  • 415
  • 2
  • 4
  • 12

3 Answers3

26

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

Martin Smith
  • 438,706
  • 87
  • 741
  • 845
  • 3
    @Ethan: Questions should be asked in **Questions** rather than Comments; so they can be answered in **Answers** instead of additional Comments. – Pieter Geerkens Dec 28 '14 at 21:39
7
select 
isnull([column1],'rollup'), 
sum([column2] )
from tableA
group by [column1] 
WITH ROLLUP
  • 4
    This does not return the correct results if `column1` contains `NULL`s. The `GROUPING` function is the correct way. ["GROUPING is used to distinguish the null values that are returned by ROLLUP, CUBE or GROUPING SETS from standard null values."](http://technet.microsoft.com/en-us/library/ms178544.aspx) – Martin Smith Oct 20 '13 at 16:31
-4
SELECT ifnull([column1],'total'),
       sum([Column2])
FROM   Tablea
GROUP  BY [Column2] WITH ROLLUP 
FelixSFD
  • 6,052
  • 10
  • 43
  • 117