Skip to content
Advertisement

Modify query so as to add new row with sum of values in some column

I have table in SQL Server like below using below code:

select col1, count(*) as col2, 
    case when col1 = 'aaa' then 'xxx'
         when col1 = 'bbb' then 'yyy'
         when col1 = 'ccc' then 'zzz'
    else 'ttt'
    end 'col3'
from table1
group by col1

col1  | col2  | col3
----------------------
aaa   | 10   | xxx
bbb   | 20   | yyy
ccc   | 30   | yyy

How can I modify my query in SQL Server so as to add new row with sum of values in col2? So I need something like below:

col1  | col2  | col3
----------------------
aaa   | 10   | xxx
bbb   | 20   | yyy
ccc   | 30   | yyy
sum   | 60   | sum of values in col2

Advertisement

Answer

You could use ROLLUP for this. The documentation explains how this works. https://docs.microsoft.com/en-us/sql/t-sql/queries/select-group-by-transact-sql?view=sql-server-ver15

select col1, count(*) as col2, 
case when col1 = 'aaa' then 'xxx'
     when col1 = 'bbb' then 'yyy'
     when col1 = 'ccc' then 'zzz'
else 'ttt'
end 'col3'
from table1
group by rollup(col1)

—EDIT— Here is the updated code demonstrating how coalesce works.

select coalesce(col1, 'sum')
    , count(*) as col2
    , case when col1 = 'aaa' then 'xxx'
        when col1 = 'bbb' then 'yyy'
        when col1 = 'ccc' then 'zzz'
        else 'ttt'
        end 'col3'
from table1
group by rollup(col1)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement