如何在 SQL 服务器中进行汇总?

How to do a Rollup in SQL Server?

我正在尝试在 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 的新手,我知道我的代码可能杂乱无章,所以我提前道歉。感谢您的帮助!

注意:不清楚 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 值的正确方法是在使用 [=13= 时使用 grouping() return '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]

参考: