Oracle所有日期按给定范围和特定跳过天数

yquaqz18  于 2023-08-04  发布在  Oracle
关注(0)|答案(3)|浏览(90)

我有from日期和to日期。我想选择每个月的日期为05、15或25的条目。例如,如果给定的日期范围是从2022年4月1日到2022年8月31日,则所需的输出应为

05-04-2022
15-04-2022
25-04-2022
.
.
.
15-08-2022
25-08-2022

字符串

ss2ws0br

ss2ws0br1#

extract函数可能就是您要查找的(see here)。
一个虚拟示例可能如下所示

with mydata as ( 
select to_date('1-APR-22','DD-MON-YY') thedate, 5 thevalue from dual union all 
select to_date('5-APR-22','DD-MON-YY') thedate, 6 thevalue from dual union all 
select to_date('15-APR-22','DD-MON-YY') thedate, 7 thevalue from dual union all 
select to_date('16-APR-22','DD-MON-YY') thedate, 8 thevalue from dual union all 
select to_date('25-APR-22','DD-MON-YY') thedate, 9 thevalue from dual union all 
select to_date('16-JUN-22','DD-MON-YY') thedate, 10 thevalue from dual union all 
select to_date('25-SEP-22','DD-MON-YY') thedate, 11 thevalue from dual 
)  select * from mydata where extract(day from thedate) in (5,15,25);

字符串
产出:

THEDATE     THEVALUE
--------- ----------
05-APR-22          6
15-APR-22          7
25-APR-22          9
25-SEP-22         11


所以,如果我没有误解你的问题的话,这似乎是你所要求的。

ezykj2lf

ezykj2lf2#

使用递归查询来产生日期。下面是一个简单的查询。它创建该范围内的所有日期,然后提取第5、15和25天。在很大的日期范围内,这可能会很慢。在这种情况下,请修改递归部分,以便首先只生成所需的日期。

with dates (dt) as
(
  select :start_date from dual
  union all
  select dt + interval '1' day
  from dates
  where dt < :end_date
)
select *
from dates
where extract(day from dt) in (5, 15, 25)
order by dt;

字符串
演示:https://dbfiddle.uk/8fuWmOUK

pb3skfrl

pb3skfrl3#

您可以用途:

SELECT ADD_MONTHS(DATE '2022-04-05', FLOOR((LEVEL - 1)/3))
       + MOD(LEVEL - 1, 3) * 10 AS dt
FROM   DUAL
CONNECT BY LEVEL <= 15

字符串
或者:

SELECT m.month + d.day - 1 AS dt
FROM   (
         SELECT ADD_MONTHS(DATE '2022-04-01', LEVEL - 1) As month
         FROM   DUAL
         CONNECT BY LEVEL <= 5
       ) m
       CROSS JOIN (
         SELECT  5 AS day FROM DUAL UNION ALL
         SELECT 15 FROM DUAL UNION ALL
         SELECT 25 FROM DUAL
       ) d


或者:

SELECT ADD_MONTHS(DATE '2022-04-05', FLOOR((LEVEL - 1)/3))
       + MOD(LEVEL - 1, 3) * 10 AS dt
FROM   DUAL
CONNECT BY
       ADD_MONTHS(DATE '2022-04-05', FLOOR((LEVEL - 1)/3))
       + MOD(LEVEL - 1, 3) * 10 < DATE '2022-09-01'


或者:

SELECT m.month + d.day - 1 AS dt
FROM   (
         SELECT ADD_MONTHS(DATE '2022-04-01', LEVEL - 1) As month
         FROM   DUAL
         CONNECT BY ADD_MONTHS(DATE '2022-04-01', LEVEL - 1) < DATE '2022-09-01'
       ) m
       CROSS JOIN (
         SELECT  5 AS day FROM DUAL UNION ALL
         SELECT 15 FROM DUAL UNION ALL
         SELECT 25 FROM DUAL
       ) d


其中所有输出:
| DT |
| ------------ |
| 2022-04-05 00:00:00 |
| 2022-04-15 00:00:00 |
| 2022-04-25 00:00:00 |
| 2022-05-05 00:00:00 |
| 2022-05-15 00:00:00 |
| 2022-05-25 00:00:00 |
| 2022-06-05 00:00:00 |
| 2022-06-15 00:00:00 |
| 2022-06-25 00:00:00 |
| 2022-07-05 00:00:00 |
| 2022-07-15 00:00:00 |
| 2022-07-25 00:00:00 |
| 2022-08-05 00:00:00 |
| 2022-08-15 00:00:00 |
| 2022-08-25 00:00:00 |
fiddle

相关问题