【问题标题】:Display hourly based data for 24 hour in SQL Server在 SQL Server 中显示 24 小时的每小时数据
【发布时间】:2019-12-29 11:29:43
【问题描述】:

我想显示过去 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

【问题讨论】:

  • 您已使用 Microsoft SQL Server 和 MySQL 标记了该问题。这些是具有不同解决方案的不同 DBMS 产品。删除无关标签。
  • 感谢您的建议,下次我会记住的

标签: asp.net sql-server database


【解决方案1】:

您可以使用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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-20
    • 2023-04-01
    • 1970-01-01
    相关资源
    最近更新 更多