在SQL Server中显示24小时的每小时数据

时间:2019-08-24 12:57:18

标签: asp.net sql-server database

我想显示最近24小时的基于小时的报告。我已经尝试过,但是问题是它只会在特定的小时包含数据的地方显示计数。

但是我想显示一个小时的计数,如果找不到计数,那么在那显示0。

select 
    datepart(hour, upload_date) as [hour], count(*)
from 
    tbl_stories
where 
    upload_date > getdate() - 1
group by 
    datepart(hour, upload_date)

输出:

hour    count
-------------
11      2
16      1
17      1

但是我想通过以下方式获得记录。

hour   count
-------------
1       0
2       0
3       5
.
.
.
.
24       1

1 个答案:

答案 0 :(得分:5)

您可以使用value()子句生成所有小时数,然后使用left join

select v.hh, count(s.upload_date)
from (values (0), (1), . . . (23)
     ) v(hh) left join
     tbl_stories s
     on datepart(hour, s.upload_date) = v.hh and
        s.upload_date > getdate() - 1
group by v.hh
order by v.hh;

请注意,小时数从0到23。

如果您不想列出时间,便捷的生成方法是递归CTE:

with hours as (
      select 1 as hh
      union all
      select hh + 1
      from hours
      where hh < 23
     )
select h.hh, count(s.upload_date)
from hours h
     tbl_stories s
     on datepart(hour, s.upload_date) = h.hh and
        s.upload_date > getdate() - 1
group by h.hh
order by h.hh;