2014-09-30 82 views
0

因此,我有一個查詢來從時間範圍的日誌表中提取錯誤計數,並顯示每分鐘的計數。即使行顯示爲0,也在SQL中顯示一個計數

select DATEADD(MI, DATEDIFF(MI, 0, errors),0), COUNT(*) from log 
where errors> '2014-07-23 17:20' 
and errors < '2014-07-23 17:25' 
group by DATEADD(MI, DATEDIFF(MI, 0, errors),0) 

如果有一分鐘沒有任何錯誤它只是忽略該行:

2014-07-23 17:20:00.000 20 
2014-07-23 17:21:00.000 20 
2014-07-23 17:23:00.000 20 
2014-07-23 17:24:00.000 19 

我怎樣才能得到它,即使沒有錯誤填充一行。例如。上面的輸出將有一排這樣的:

2014-07-23 17:22:00.000 0 
+0

在這種情況下,它是n ot顯示,因爲2014-07-23 17:22:00.000不是從DATEADD(MI,DATEDIFF(MI,0,errors),0)返回的。 – Hatjhie 2014-09-30 03:04:26

+0

您需要在時間範圍內創建所有分鐘的表格/視圖,並用您的表格「LEFT JOIN」連接。 – 2014-09-30 03:06:50

回答

1

生成您需要填寫的日期範圍:

-- test table, should be the results from your query 
declare @t table (d datetime, c int) 
insert @t values 
('2014-07-23 17:20:00.000', 20), 
('2014-07-23 17:21:00.000', 20), 
('2014-07-23 17:23:00.000', 20), 
('2014-07-23 17:24:00.000', 19); 

with cte (d) as (
    select cast('2014-07-23 17:20' as datetime) as d 
    union all 
    select DATEADD(minute,1,d) d 
    from cte where d < cast('2014-07-23 17:25' as datetime) 
) 

select isnull(t.d, cte.d), isnull(c,0) 
from cte 
left join @t t on cte.d = t.d 

輸出:

----------------------- ----------- 
2014-07-23 17:20:00.000 20 
2014-07-23 17:21:00.000 20 
2014-07-23 17:22:00.000 0 
2014-07-23 17:23:00.000 20 
2014-07-23 17:24:00.000 19 
2014-07-23 17:25:00.000 0 

在你的情況下,查詢大概會是這樣的:

with cte (d) as (
    select cast('2014-07-23 17:20' as datetime) as d 
    union all 
    select DATEADD(minute,1,d) d 
    from cte where d < cast('2014-07-23 17:25' as datetime) 
) 
select isnull(t.d, cte.d), isnull(c,0) 
from cte 
left join(
    select DATEADD(MI, DATEDIFF(MI, 0, errors),0) as d, COUNT(*) from log 
    where errors> '2014-07-23 17:20' 
    and errors < '2014-07-23 17:25' 
    group by DATEADD(MI, DATEDIFF(MI, 0, errors),0) 
    ) derived on cte.d = derived.d