How to add a subtotal row in sql This comes from: http://stackoverflow.com/questions/19387650/how-to-add-a-subtotal-row-in-sql Name Score A 2 B 3 A 1 B 3 Name Score A 2 A 1 Subtotal 3 B 3 B 3 Subtotal 6 create table scores (name varchar(10), Score integer) insert into scores values ('A', 2) go insert into scores values ('B', 3) go insert into scores values ('A', 1) go insert into scores values ('B', 3) go with cte as ( select *, row_number() over(order by newid()) as rn from scores ) select case when grouping(c.rn) = 1 then 'Subtotal' else c.Name end as Name, sum(c.Score) as Score from cte as c group by grouping sets ((c.Name), (c.Name, c.rn)) order by c.Name; -- OR with cte as ( select *, row_number() over(order by newid()) as rn from scores ) select case when grouping(c.rn) = 1 then 'Subtotal' else c.Name end as Name, sum(c.Score) as Score from cte as c group by rollup(c.Name, c.rn) having grouping(c.Name) = 0 order by c.Name; oracle equivalent on the same scores table: with cte as ( select scores.*, row_number() over(order by 2) as rn from scores ) select case when grouping(c.rn) = 1 then 'Subtotal' else c.Name end as Name, sum(c.Score) as Score from cte c group by grouping sets ((c.Name), (c.Name, c.rn)) order by c.Name