如何在SQL Server中进行汇总?

时间:2017-02-03 22:12:54

标签: sql-server rollup

我正在尝试在MS SQL上完成Rollup,以便我的列“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的新手,我知道我的代码可能没有组织,所以我提前道歉。我很感激帮助!

1 个答案:

答案 0 :(得分:0)

注意:目前还不清楚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()时使用'Total'返回null而不是grouping sets

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]

参考: