2017-02-03 65 views
0

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

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,我知道我的代码可能是混乱的,所以我提前道歉。我感谢帮助!

+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] 

参考:

+0

这是完美的!感谢您花时间帮助我。欣赏它! – Alex