【问题标题】:Insert a row for each month in the range [duplicate]在范围内为每个月插入一行 [重复]
【发布时间】:2022-01-19 21:41:24
【问题描述】:

我想在 Oracle 中制作我的表

  +----+------------+------------+
  |  N |    Start   |     End    | 
  +----+------------+------------+
  |  1 | 2018-01-01 | 2018-05-31 | 
  |  1 | 2018-01-01 | 2018-06-31 |
  +----+------------+------------+

进入,看起来很傻我需要在第一个表中每个月的范围内为每个月插入一行

  +----+------------+
  |  N |    month|  |   
  +----+------------+
  |  1 | 2018-01-01 | 
  |  1 | 2018-01-01 | 
  |  1 | 2018-02-01 | 
  |  1 | 2018-02-01 | 
  |  1 | 2018-03-01 | 
  |  1 | 2018-03-01 | 
  |  1 | 2018-04-01 | 
  |  1 | 2018-04-01 | 
  |  1 | 2018-05-01 | 
  |  1 | 2018-05-01 | 
  |  1 | 2018-06-01 | 
  +----+------------+

我一直在尝试关注SQL: Generate Record Per Month In Date Range,但我没有找到想要的结果。

感谢您的帮助

【问题讨论】:

  • 只有当您解释了从 A 到 B 的规则时...为什么有 4 行 1 月行,2 行 2 月 - 5 月,只有 1 行 6 月?什么是N?两个源行中真的是 1 吗?
  • 我不记得2018年有31.6。
  • N的目的是什么?它始终具有相同的值。
  • @littlefoot 抱歉打错了

标签: sql oracle plsql


【解决方案1】:

您可以使用递归 CTE。例如:

with
n (s, e, cur) as (
  select s, e, s from t
 union all
  select s, e, add_months(cur, 1)
  from n
  where add_months(cur, 1) < e
)
select cur from n;

结果:

CUR
---------
01-JAN-18
01-JAN-18
01-FEB-18
01-FEB-18
01-MAR-18
01-MAR-18
01-APR-18
01-APR-18
01-MAY-18
01-MAY-18
01-JUN-18

请参阅db<>fiddle 的运行示例。

【讨论】:

    【解决方案2】:

    我的最佳猜测是你想在你的表中显示所有月初startend之间的区间。

    create table t1 as
    select date'2018-01-01' start_d, date'2018-05-31' end_d from dual union all
    select date'2018-01-01' start_d, date'2018-06-30' end_d from dual;
    
    with cal as
    (select add_months(date'2018-01-01', rownum-1) month_d
    from dual connect by level <= 12)
    select  cal.month_d from cal
    join t1 on cal.month_d between t1.start_d and t1.end_d
    order by 1;
    
    MONTH_D            
    -------------------
    01.01.2018 00:00:00
    01.01.2018 00:00:00
    01.02.2018 00:00:00
    01.02.2018 00:00:00
    01.03.2018 00:00:00
    01.03.2018 00:00:00
    01.04.2018 00:00:00
    01.04.2018 00:00:00
    01.05.2018 00:00:00
    01.05.2018 00:00:00
    01.06.2018 00:00:00
    

    因此,您对 1 月份的预期可能存在剪切和粘贴错误。

    其他几点

    • 不要使用保留字作为列名的start

    • 使用DATE 格式存储日期以避免无效条目,例如2018-06-31

    【讨论】:

      猜你喜欢
      • 2014-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-07
      • 2023-01-12
      • 1970-01-01
      • 2021-09-21
      相关资源
      最近更新 更多