我们有一个带有 DATE 列的表。我们如何编写一个脚本来返回 future n 年内我们没有给定周末日期的任何周末日期(星期六或星期日)?
最佳答案
要获得今天和今天 + 365 天之间的所有周末:
select as_of_date
from
(
select
rownum,
sysdate + rownum - 1 as as_of_date
from dual
connect by rownum <= (sysdate+365) - sysdate
) sub
where to_char(as_of_date, 'DY', 'nls_date_language=AMERICAN') in ('SAT', 'SUN')
要排除给定表中存在的日期,只需添加“并且不存在(从 your_table y 中选择 1,其中 y.the_date = as_of_date)”或类似内容,如下所示:
select as_of_date
from
(
select
rownum,
sysdate + rownum - 1 as as_of_date
from dual
connect by rownum <= (sysdate+365) - sysdate
) sub
where to_char(as_of_date, 'DY', 'nls_date_language=AMERICAN') in ('SAT', 'SUN')
and not exists (select 1 from my_table myt where myt.as_of_date = sub.as_of_date)
可以简化为不使用子查询,只需将“as_of_date”列的出现次数更改为“sysdate + rownum - 1”就可以了
还值得注意的是,我在需要获取所有日期时使用了该查询,而不仅仅是周末。我在答案中所做的只是排除最外层查询中的周末。如果您不想返回不需要的数据,我确信最里面的查询可以更改为不经过 365 天,而只能通过周末的数量(即使用 where rownum < 365/5 并检索日期 + ( 6,7)从周六或周日开始),但我认为这不是一个大的性能问题,所以我并不担心
关于sql - Oracle - 查找不在表中的所有日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14263156/