【问题标题】:How to do a Rollup in SQL Server?如何在 SQL Server 中进行汇总?
【发布时间】:2017-06-21 09:22:51
【问题描述】:

我正在尝试在 MS SQL 上完成汇总,以便我的列“DET”在最后一行有一个完整的总和。 Arrive 列包含字符,所以如果可能的话,我只是试图让该列中的总行为 NULL。当我做Group by Date, DET, Arrive with Rollup 时,它会进行小计,将每个日期的总数相加(如果可能的话,我不想要)。

Select Date = isnull(Date,'Total'), DET, Arrive = isnull(Arrive, 'Total') from
    (select convert(VARCHAR, EventDate1, 112) as Date,
    sum(CASE WHEN Depart = 'DET' and (ETStatus = 'F' or ETStatus = 'L' or ETStatus = 'C') THEN 1 ELSE 0 END) as DET, Arrive
    from TicketCoupons
    where EventDate1 >= '20160601' and EventDate1 <= '20160709'
    group by convert(VARCHAR, EventDate1, 112), Arrive
    )mytable
    where PIT > '0'
    group by Rollup(Date), DET, Arrive
    order by Date

另外,我是 SQL 新手,我知道我的代码可能杂乱无章,所以我提前道歉。感谢您的帮助!

【问题讨论】:

  • 能否添加示例数据和预期结果

标签: sql-server rollup


【解决方案1】:

注意:尚不清楚PIT 的来源,因此不在下面的答案中。

您可以改为使用grouping sets

select 
      [Date]= isnull(convert(varchar(8), EventDate1, 112),'Total')
    , DET = sum(case 
                when Depart = 'DET'and ETStatus in ('F','L','C') 
                  then 1
                else 0
                end)
    , Arrive= Arrive
  from TicketCoupons
  where EventDate1 >= '20160601'
    and EventDate1 <= '20160709'
  group by grouping sets (
      (convert(varchar(8), EventDate1, 112), Arrive)
    , ()
  )
  order by [Date]

在这种情况下处理null值的正确方法是在使用grouping sets时使用grouping()返回'Total'而不是null

select 
      [Date]= case when grouping(convert(varchar(8), EventDate1, 112)) = 0 
                  then 'unknown' -- values of null will return as 'unknown'
                else 'Total' -- total row will return 'Total' as requested
                end
    , DET = sum(case 
                when Depart = 'DET'and ETStatus in ('F','L','C') 
                  then 1
                else 0
                end)
    , Arrive= case when grouping(Arrive) = 0
                  then 'unknown' -- values of null will return as 'unknown'
                else null -- total row will return `null` as requested
                end
                */
  from TicketCoupons
  where EventDate1 >= '20160601'
    and EventDate1 <= '20160709'
  group by grouping sets (
      (convert(varchar(8), EventDate1, 112), Arrive)
    , ()
  )
  order by [Date]

参考:

【讨论】:

  • 这太完美了!感谢您花时间帮助我。欣赏!
猜你喜欢
  • 2014-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-10
  • 1970-01-01
  • 1970-01-01
  • 2021-06-28
  • 2015-03-02
相关资源
最近更新 更多