SQL汇总到分组表的总和

时间:2018-04-23 18:20:45

标签: sql sql-server group-by rollup

我有一个按'组类型'分组的表格。我需要的是最后一行显示 Total 行中上述行中值的总和。

以下是目前的代码,但我不确定如何一次性汇总多个字段。

实际

ROLLUP-1

预期结果

enter image description here

我是否需要添加另一个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]

1 个答案:

答案 0 :(得分:1)

我会在聚合之前做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), () );