即使行显示0,也在SQL中显示时间范围的计数

时间:2014-09-30 02:59:42

标签: sql sql-server

所以我有一个查询来从日志表中提取一个时间范围的错误数,并显示每分钟的计数。

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

1 个答案:

答案 0 :(得分: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