Grouping records hour by hour or day by day and filling gaps with zero or null

后端 未结 1 1428
执笔经年
执笔经年 2020-12-06 08:17

I have written a query that counts records hour by hour:

select TO_CHAR(copied_timestamp, \'YYYY-MM-DD HH24\'),count(*) from req group by
TO_CHAR(copied_time         


        
相关标签:
1条回答
  • 2020-12-06 08:24

    try:
    first query (by hour):

    with t as (
      select mnd + ((level-1)/24) ffffd
      from
      (select trunc(min(copied_timestamp),'hh') mnd, trunc(max(copied_timestamp),'hh') mxd from req) v
      connect by mnd + ((level-1)/24) <= mxd
      )
    select to_char(trunc(d1, 'hh'), 'yyyy-mm-dd hh24'), count(d2) from 
    (select nvl(copied_timestamp, ffffd) d1, copied_timestamp d2 from req right outer join (
      select ffffd from t) ad on ffffd = trunc(copied_timestamp, 'hh'))
    group by trunc(d1, 'hh');
    

    second query (by day):

    with t as (
          select mnd + level-1 ffffd
          from
          (select trunc(min(copied_timestamp),'dd') mnd, trunc(max(copied_timestamp),'dd') mxd from req) v
          connect by mnd + level-1 <= mxd
          )
        select to_char(trunc(d1, 'dd'), 'yyyy-mm-dd'), count(d2) from 
        (select nvl(copied_timestamp, ffffd) d1, copied_timestamp d2 from req right outer join (
          select ffffd from t) ad on ffffd = trunc(copied_timestamp, 'dd'))
        group by trunc(d1, 'dd');
    

    third query (by month):

    with t as (
          select add_months(mnd, level-1) ffffd
          from
          (select trunc(min(copied_timestamp),'mm') mnd, trunc(max(copied_timestamp),'mm') mxd from req) v
          connect by add_months(mnd, level-1) <= mxd
          )
        select to_char(trunc(d1, 'mm'), 'yyyy-mm'), count(d2) from 
        (select nvl(copied_timestamp, ffffd) d1, copied_timestamp d2 from req right outer join (
          select ffffd from t) ad on ffffd = trunc(copied_timestamp, 'mm'))
        group by trunc(d1, 'mm');
    
    0 讨论(0)
提交回复
热议问题