2014-06-24 64 views
0

我有以下查詢,我按照日期細分了事故。SQL CASE將語句數據組織到一個查詢中

select t.range as [Date Range], count(*) as Accidents 
from (
    select case 
     when (MONTH(accidentdatetime) >= 6 AND YEAR(accidentdatetime) = 2013) and (MONTH(accidentdatetime) <= 12 AND YEAR(accidentdatetime) = 2013) then 'Other' 
     when MONTH(accidentdatetime) = 1 AND YEAR(accidentdatetime) = 2014 then 'January' 
     when MONTH(accidentdatetime) = 2 AND YEAR(accidentdatetime) = 2014 then 'Feburary' 
     when MONTH(accidentdatetime) = 3 AND YEAR(accidentdatetime) = 2014 then 'March' 
     when MONTH(accidentdatetime) = 4 AND YEAR(accidentdatetime) = 2014 then 'April' 
     when MONTH(accidentdatetime) = 5 AND YEAR(accidentdatetime) = 2014 then 'May' 
     end as range 
    from Accidents 
    where accidentdatetime between '06/30/2013' and '05/31/2014' 
    ) t 
group by t.range 

enter image description here

我試圖理解我如何進一步打破下來到我基於數據庫的OSHA領域可以進一步指定類型的事故。喜歡的東西:

select t.range as [Date Range],count(*) as [Accidents], (SELECT count(*) FROM Accidents WHERE OSHAClassificationID IN (2,4)) as [Lost Time] 
from (
    select case 
     when (MONTH(accidentdatetime) >= 6 AND YEAR(accidentdatetime) = 2013) and (MONTH(accidentdatetime) <= 12 AND YEAR(accidentdatetime) = 2013) then 'Other' 
     when MONTH(accidentdatetime) = 1 AND YEAR(accidentdatetime) = 2014 then 'January' 
     when MONTH(accidentdatetime) = 2 AND YEAR(accidentdatetime) = 2014 then 'Feburary' 
     when MONTH(accidentdatetime) = 3 AND YEAR(accidentdatetime) = 2014 then 'March' 
     when MONTH(accidentdatetime) = 4 AND YEAR(accidentdatetime) = 2014 then 'April' 
     when MONTH(accidentdatetime) = 5 AND YEAR(accidentdatetime) = 2014 then 'May' 
     end as range 
    from Accidents 
    where accidentdatetime between '06/30/2013' and '05/31/2014' 
    ) t 
group by t.range 

enter image description here

但我試圖創建另一列僅指定一個類型事故中不按日期過濾,並且只顯示在數據庫中佔所有失去的時間事故的次數我的查詢..

有沒有辦法在一個查詢中按日期範圍和事故類型進行過濾?

回答

1

您需要返回一個標誌來指示記錄是否在您的osha範圍內但在月份過濾器內。然後用1將這些記錄進行總結,以獲得您的代碼子集中的計數。

select t.range as [Date Range],count(*) as [Accidents], 
    [Lost Time]=sum(OSHAFlag) 
from (
    select 
     OSHAFlag=case when Accidents.OSHAClassificationID IN(2,4) THEN 1 ELSE 0 END, 
     case 
     when (MONTH(accidentdatetime) >= 6 AND YEAR(accidentdatetime) = 2013) and (MONTH(accidentdatetime) <= 12 AND YEAR(accidentdatetime) = 2013) then 'Other' 
     when MONTH(accidentdatetime) = 1 AND YEAR(accidentdatetime) = 2014 then 'January' 
     when MONTH(accidentdatetime) = 2 AND YEAR(accidentdatetime) = 2014 then 'Feburary' 
     when MONTH(accidentdatetime) = 3 AND YEAR(accidentdatetime) = 2014 then 'March' 
     when MONTH(accidentdatetime) = 4 AND YEAR(accidentdatetime) = 2014 then 'April' 
     when MONTH(accidentdatetime) = 5 AND YEAR(accidentdatetime) = 2014 then 'May' 
     end as range 
    from Accidents 
    where accidentdatetime between '06/30/2013' and '05/31/2014' 
    ) t 
group by t.range 
+0

美麗,謝謝! – Trevor