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

2skhul33  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(293)

我有以下格式查询:

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
status  count   hour    datee
SUCCESS  1  1   8/6/2020
SUCCESS  2  2   8/6/2020
SUCCESS 5   3   8/6/2020
SUCCESS 2   4   8/6/2020
SUCCESS 3   5   8/6/2020
SUCCESS 2   8   8/6/2020

所需输出应为所有小时

status  count   hour    datee 
    SUCCESS  1  1   8/6/2020
    SUCCESS  2  2   8/6/2020
    SUCCESS 5   3   8/6/2020
    SUCCESS 2   4   8/6/2020
    SUCCESS 3   5   8/6/2020
    SUCCESS 0   6   8/6/2020
    SUCCESS 0   7   8/6/2020
    SUCCESS 2   8   8/6/2020

我的意思是小时(6,7)应该有(0)的值。

mkshixfv

mkshixfv1#

您的语法看起来像postgres,它具有 generate_series() :

select gs.hh, ultd.status, count(ultd.status) as count
from generate_series(current_date, now(), interval '1 hour') gs(hh) left join
     zainksa_mobileapp.user_logging_table_detail ultd
     on ultd.creationtime >= gs.hh and
        ultd.creationtime < gs.hh + interval '1 hour' and
        ultd.status = 'SUCCESS' 
group by gs.hh, ultd.status
order by hour asc
k0pti3hp

k0pti3hp2#

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;

相关问题