Search code examples
sqlsql-servergroup-byrollup

SQL Rollup to Sum Totals of a Grouped Table


I have a table that is grouped by 'Group Type'. What I need is for the last row to display the sum of the values in the above rows in the Total row.

Below is the code currently but I am not sure how to sum multiple fields at once.

Actual

ROLLUP-1

Expected Result

enter image description here

Do I need to add another CASE statement to

select
CASE when GROUP_TYPE is null then 'Total' ELSE GROUP_TYPE END as 'Group Type',    
Sum_Amount, TotalER, [Discount Report]
    from  
    (select GROUP_TYPE, sum(cast(AMOUNT as float)) as Sum_Amount FROM [dbo].[a] 
        where cast(ACTIVITY_DATE as date) between @startdate and @enddate
             group by GROUP_TYPE with rollup) a
left join
    (select [Charge Group] , sum(cast([Earned Revenue] as float)) as 
    TotalER, sum(cast(Discount as float)) as 'Discount Report'
        from [dbo].[er] group by [Charge Group]) er
on
    a.GROUP_TYPE = er.[Charge Group]

select sum(cast([er] as float)) from [dbo].[er]

Solution

  • I would do a union all before the aggregation. This makes it easier to specify the multiple aggregation sets:

    select coalesce(group_type, 'Total') as group_type, -- the easy way
           sum(amount) as sum_amount, sum(er) as totaler, sum(discount) as discount
    from ((select group_type, cast(amount as float) as Amount, 0 as ER, 0 as discount
           from [dbo].a
           where cast(ACTIVITY_DATE as date) between @startdate and @enddate
          ) union all
          (select [Charge Group], 0, cast([Earned Revenue] as float) as er, cast(Discount as float)
           from [dbo].er 
           where cast(ACTIVITY_DATE as date) between @startdate and @enddate
          )
         ) aer
    group by grouping sets ( (group_type), () );