SQL 汇总到分组的总和 Table

SQL Rollup to Sum Totals of a Grouped Table

我有一个按 'Group Type' 分组的 table。我需要的是最后一行在 Total 行中显示上述行中值的总和。

下面是目前的代码,但我不确定如何一次对多个字段求和。

实际

预期结果

我需要再添加一个 CASE 语句吗?

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]

我会在 聚合之前进行 union all 。这使得指定多个聚合集更容易:

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), () );