Sql 按小时分组,如果没有数据,则为0

Sql 按小时分组,如果没有数据,则为0,sql,Sql,我有以下格式查询: select status as status, count(*) as count, EXTRACT( hour from creationtime ) AS hour, creationtime::date as datee from user_logging_table_detail where creationtime::date = current_date and status = 'SUCC

我有以下格式查询:

select status as status,
    count(*) as count,
    EXTRACT(
        hour
        from creationtime
    ) AS hour,
    creationtime::date as datee
from user_logging_table_detail
where creationtime::date = current_date
    and status = 'SUCCESS'
group by hour,
    creationtime::date,
    status
order by hour asc
状态计数小时日期 成功1 1 8/6/2020 成功2 8/6/2020 成功5 3 8/6/2020 成功2 4 8/6/2020 成功3 5 8/6/2020
SUCCESS 2 8 8/6/2020您的语法看起来像Postgres,它具有方便的generate_系列:


Gordon Linoff的解决方案很优雅,但我认为我应该提供一个通用的替代方案,它不依赖于特定的Postgres功能:

WITH t AS
(
    SELECT m * 10 + n h
    FROM (VALUES (0), (1), (2)) v1(m)
    CROSS JOIN (VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9)) v2(n)
    where m * 10 + n < 25
)
select t.h, status as status,
    count(*) as count,
    EXTRACT(
        hour
        from creationtime
    ) AS hour,
    creationtime::date as datee
from t
 left join user_logging_table_detail
  on EXTRACT(hour from creationtime ) = t.h
   and creationtime::date = current_date
   and status = 'SUCCESS'
group by hour,
    creationtime::date,
    status
order by t.h;


用您正在使用的数据库标记您的问题。hi bro当执行时,我们得到以下错误:表ultd第4行的子句条目中缺少:on ultd.creationtime>=gs.hh,这是一个很好的解决方案。我真的从中学到了一些东西。假设这确实是研究生,也就是说。
WITH t AS
(
    SELECT m * 10 + n h
    FROM (VALUES (0), (1), (2)) v1(m)
    CROSS JOIN (VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9)) v2(n)
    where m * 10 + n < 25
)
select t.h, status as status,
    count(*) as count,
    EXTRACT(
        hour
        from creationtime
    ) AS hour,
    creationtime::date as datee
from t
 left join user_logging_table_detail
  on EXTRACT(hour from creationtime ) = t.h
   and creationtime::date = current_date
   and status = 'SUCCESS'
group by hour,
    creationtime::date,
    status
order by t.h;