oracle 使用日期范围为每个月生成一行

wljmcqd8  于 2023-05-06  发布在  Oracle
关注(0)|答案(1)|浏览(254)

我有下面的代码,它生成一个月的第一行。正如你所看到的,我有硬编码的月数(200)。如何修改代码以删除硬编码值(200)并将其替换为结束日期(即04.30.2023)。这将生成最后一行作为APR 2023。

WITH
  test_data
  AS
   (SELECT TO_DATE ('01.03.2008', 'DD.MM.YYYY') AS mnth FROM DUAL),
  mnth_data (mnth, max_mnth)
  AS
   (SELECT mnth, ADD_MONTHS (mnth, 200) AS max_mnth FROM test_data
    UNION ALL
    SELECT ADD_MONTHS (mnth, 1) AS mnth, max_mnth
     FROM mnth_data
    WHERE mnth < max_mnth)
SELECT mnth
 FROM mnth_data
kadbb459

kadbb4591#

将结束日期放入查询中:

WITH test_data (month, end_month) AS (
  SELECT DATE '2008-03-01', DATE '2023-04-30' FROM DUAL
UNION ALL
  SELECT ADD_MONTHS(month, 1), end_month
  FROM   test_data
  WHERE  ADD_MONTHS(month, 1) <= end_month
)
SELECT month
FROM   test_data

或者,如果要生成截至当前月份的日期,则:

WITH test_data (month, end_month) AS (
  SELECT DATE '2008-03-01', TRUNC(SYSDATE, 'MM') FROM DUAL
UNION ALL
  SELECT ADD_MONTHS(month, 1), end_month
  FROM   test_data
  WHERE  ADD_MONTHS(month, 1) < end_month
)
SELECT month
FROM   test_data;

两者输出:
| 月|
| --------------|
| 2008-03-01 00:00:00|
| 2008-04-01 00:00:00|
| 2008-05-01 00:00:00|
| ......这是什么?|
| 2019 -02- 21 00:00:00|
| 2019 -03-01 00:00:00|
| 2019 -04-01 00:00:00|
fiddle

相关问题