Oracle - 列出每个月的每一天和几个小时

Oracle - List every single day with hours in the month

我做了一些仪表板,我发现我没有任何 table 包括我需要的所有日期。我的子查询按 DATE (DD.MM,YYYY) 和 HOURS (HH24) 连接。但是我被模板卡住了。

我通过

列出了一个月中的所有日期
select to_date('1.' || to_CHAR(sysdate, 'MM.YYYY'), 'dd.mm.yyyy') + level - 1 as month
   from dual
  connect by level <= TO_CHAR(LAST_DAY(sysdate), 'DD')

并且还通过

列出了当天的所有营业时间
select to_date(to_char(sysdate, 'DD.MM.YYYY'), 'dd.mm.yyyy') + 1 / 24*(level - 1)
   from dual
  connect by level <= 24

当我在一个月内将它与 rownum = 1 结合使用时,我只有 1 天可以正常工作...

select to_date(to_char(mesic, 'DD.MM.YYYY'), 'dd.mm.yyyy') + 1 / 24*(level - 1)
   from 
(select *
           from (select to_date('1.' || to_CHAR(sysdate, 'MM.YYYY'), 'dd.mm.yyyy') + level - 1 as mesic
                   from dual
                  connect by level <= TO_CHAR(LAST_DAY(sysdate), 'DD'))
          where rownum = 1)

  connect by level <= 24

然而,当我擦除 rownum 条件时,我得到了最大行数的错误。

按照我的逻辑,应该是 24(小时)*31(当月的天数)= 744。我的休闲仪表板报告通常有 5000 行,所以这应该不是问题。

谢谢大家的指点

如果你想生成当月的所有小时数,你可以这样做:

with cte (dt) as (
    select trunc(sysdate, 'month') from dual
    union all
    select dt + interval '1' hour 
    from cte 
    where dt + interval '1' hour < trunc(sysdate, 'month') + interval '1' month
)
select * from cte   

我们可以通过分别生成天数和小时数来减少迭代次数,然后 cross-joining 它们:

with 
    days (dy) as (
        select trunc(sysdate, 'month') from dual
        union all
        select dy + interval '1' day 
        from days 
        where dy + interval '1' day < trunc(sysdate, 'month') + interval '1' month
    ),
    hours (hh) as (
        select 0 from dual
        union all 
        select hh + 1 from hours where hh < 23
    )
select d.dy + h.hh  * interval '1' hour dt
from days d
cross join hours h

对我来说,它看起来很简单

select trunc(sysdate, 'mm') + (level - 1) / 24 datum
from dual
connect by level <= (add_months(trunc(sysdate, 'mm'), 1) - trunc(sysdate, 'mm')) * 24;

DATUM
----------------
01.08.2020 00:00
01.08.2020 01:00
01.08.2020 02:00
<snip>
31.08.2020 21:00
31.08.2020 22:00
31.08.2020 23:00

744 rows selected.