我有以下表格和数据:
CREATE TABLE customer_wer(
id_customer NUMBER,
name VARCHAR2(10),
surname VARCHAR2(20),
date_from DATE,
date_to DATE NOT NULL,
CONSTRAINT customer_wer_pk PRIMARY KEY (id_customer, data_from));
INSERT INTO customer_wer VALUES (4, 'Karolina', 'Komuda', '01-JAN-00', '31-MAR-00');
INSERT INTO customer_wer VALUES (4, 'Karolina', 'Komuda', '01-APR-00', '30-JUN-00');
INSERT INTO customer_wer VALUES (4, 'Karolina', 'Komuda', '15-JUN-00', '30-SEP-00');
INSERT INTO customer_wer VALUES (4, 'Karolina', 'Komuda', '01-OCT-00', '31-DEC-00');
INSERT INTO customer_wer VALUES (4, 'Karolina', 'Komuda', '01-JAN-01', '31-MAR-01');
INSERT INTO customer_wer VALUES (4, 'Karolina', 'Komuda', '01-APR-01', '30-JUN-01');
INSERT INTO customer_wer VALUES (4, 'Karolina', 'Komuda', '01-JUL-01', '5-OCT-01');
INSERT INTO customer_wer VALUES (4, 'Karolina', 'Komuda', '01-OCT-01', '31-DEC-01');
我需要SELECT
查询来查找日期重叠的记录。这意味着在上面的例子中,我应该在结果中有四个记录
number
2
3
7
8
提前谢谢你。 我正在使用Oracle DB。
答案 0 :(得分:2)
之前的答案并不考虑t2完全在t1
范围内的情况select * from t t1
join t t2 on (t1.datefrom > t2.datefrom and t1.datefrom < t2.dateto )
or (t1.dateto > t2.datefrom and t1.dateto < t2.dateto )
or (t1.dateto > t2.dateto and t1.datefrom < t2.datefrom)
答案 1 :(得分:0)
试试这个:
select * from t t1
join t t2 on (t1.datefrom > t2.datefrom and t1.datefrom < t2.dateto)
or (t1.dateto > t2.datefrom and t1.dateto < t2.dateto)
谢谢你这个例子。修改后它正在运行:
SELECT *
FROM customer_wer k
JOIN customer_wer w
ON k.id_customer = w.id_customer
WHERE (k.date_from > w.date_to AND k.date_from < w.date_to)
OR (k.date_to > w.date_from AND k.date_to < w.date_to);
答案 2 :(得分:0)
如果每个开始日期小于或等于其他记录的结束日期,则它将在该范围内。
如果开始日期1小于结束日期2且开始日期2小于结束日期1。
SELECT *
FROM t t1
JOIN t t2 ON (t1.datefrom <= t2.dateto)
AND (t2.datefrom <= t1.dateto)
答案 3 :(得分:0)
类似于@Ben的答案...但检查重叠==天以及检查身份以确保它是唯一的。
select * from seasons t1
join seasons t2 on (t1.season_open >= t2.season_open and t1.season_open <= t2.season_close and t1.id != t2.id)
or (t1.season_close >= t2.season_open and t1.season_close <= t2.season_close and t1.id != t2.id)
or (t1.season_close >= t2.season_close and t1.season_open <= t2.season_open and t1.id != t2.id)
答案 4 :(得分:0)
在我有很多数据的情况下,通过这种方式获得了更好的性能:
select *
from (
select id_customer,
name,
surname,
date_from,
date_to,
lead(id_customer) over (partition by id_customer order by date_from) id_customer1,
lead(name) over (partition by id_customer order by date_from) name1,
lead(surname) over (partition by id_customer order by date_from) surname1,
lead(date_from) over (partition by id_customer order by date_from) date_from1,
lead(date_to) over (partition by id_customer order by date_from) date_to1
from customer_wer)
where date_from1 <= date_to