2017-02-03 60 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