生成您需要填寫的日期範圍:
-- 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
來源
2014-09-30 03:08:43
jpw
在這種情況下,它是n ot顯示,因爲2014-07-23 17:22:00.000不是從DATEADD(MI,DATEDIFF(MI,0,errors),0)返回的。 – Hatjhie 2014-09-30 03:04:26
您需要在時間範圍內創建所有分鐘的表格/視圖,並用您的表格「LEFT JOIN」連接。 – 2014-09-30 03:06:50