SQL查询以查找两个日期之间的日期

3

我有一个问题,希望能够获取在两个日期之间(即开始和结束日期)记录的日期。

我有一个表格,其中包含以下记录:

CREATE TABLE t (a int, b date, c date);

insert into t values(1, to_date( '01-jan-2015'), to_date( '15-jan-2015'));
insert into t values(2, to_date( '03-jan-2015'), to_date( '10-jan-2015'));
insert into t values(3, to_date( '12-jan-2015'), to_date( '25-jan-2015'));
insert into t values(4, to_date( '20-jan-2015'), to_date( '01-feb-2015'));
insert into t values(5, to_date( '05-feb-2015'), to_date( '10-feb-2015'));

有没有一种使用SELECT语句来确定在该表中给定的日期范围内存在哪些日期的方法?例如:'01-jan-2015' to_date '15-jan-2015'之间的值已经存在。但是,'03-jan-2015'和'12-jan-2015'的两个值再次被记录了。(尽管这些在('01-jan-2015' to_date '15-jan-2015')之间已经被定义过) 因此,我需要获得输出"values for start_date "'03-jan-2015' is already logged",而不需要在查询中提供日期范围。也就是说,它应该自动提取给定值的记录。 这假设当日期范围重叠时,它将消除日期范围之间的值的重载 希望这样说有意义。请帮助我解决这个问题。
谢谢,Shruthi

这几乎是相同的情况,您可以稍微调整一下以适用于您的问题... https://stackoverflow.com/questions/48755634/select-between-two-date/48756731#48756731 - GaryL
2个回答

2

试试这个

select * FROM AnyTable WHERE 
              start_date  <= '03-jan-2015' and end_date  >= '03-jan-2015'

2
尝试使用以下查询,它将列出所有重叠的条目。
SELECT  *
FROM    t as t1
WHERE EXISTS (
        SELECT  1
        FROM    t as t2
        WHERE   t1.a != t2.a
            AND t1.b <= t2.c AND t1.c >= t2.b
    )

或者尝试使用左连接

SELECT  t1.*,t2.a as overlap_id
FROM    t as t1
LEFT JOIN t as t2   ON t1.a > t2.a
            AND t1.b <= t2.c AND t1.c >= t2.b
WHERE   t2.a IS NOT NULL

a   b           c           overlap_id
--------------------------------------
2   2015-01-03  2015-01-10  1         --2 overlapped with 1
3   2015-01-12  2015-01-25  1         --3 overlapped with 1
4   2015-01-20  2015-02-01  3         --4 overlapped with 3

谢谢 Abdul。但是,我该如何获取在重叠条目之间(如果已登录)创建的记录。即,我需要仅从上述给定数据中推导出“'03-jan-2015'”的条目,而不需要提供日期范围。 - Shruthi
在您提供的数据中,记录1与记录2重叠,反之亦然;同时记录3与记录4重叠,反之亦然。 - Abdul Rasheed
同时,记录3与1和4都有重叠。 - Abdul Rasheed

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接