【问题标题】:Displaying a count in SQL for timerange even if rows show 0即使行显示 0,也在 SQL 中显示时间范围的计数
【发布时间】:2014-09-30 11:08:43
【问题描述】:

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

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

【问题讨论】:

  • 在这种情况下,它没有显示,因为 2014-07-23 17:22:00.000 没有从 DATEADD(MI, DATEDIFF(MI, 0, errors),0) 返回。
  • 您需要创建一个包含您的时间范围内所有分钟的表格/视图,并使用您的表格LEFT JOIN它。

标签: sql sql-server


【解决方案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

【讨论】:

    猜你喜欢
    • 2017-12-14
    • 2017-04-29
    • 2021-07-05
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-09
    相关资源
    最近更新 更多