我有桌子
id | id_employee | start_date | enddate
---------------------------------------------
1 | A | 01/04/2018 | 05/04/2018
2 | B | 03/04/2018 | 08/04/2018
3 | A | 02/04/2018 | 05/04/2018
4 | C | 04/04/2018 | 06/04/2018
5 | B | 05/04/2018 | 08/04/2018
我想根据日期范围(从start_date到end_date)进行选择,其中id_employee具有重复数据(在日期范围内发生冲突)
我可以使用什么查询
答案 0 :(得分:2)
SELECT `id`, `id_employee`
FROM Table1
WHERE id_employee IN (
SELECT T1.id_employee
FROM `Table1` T1
INNER JOIN
`Table1` T2
ON T1.id_employee=T2.id_employee
AND T1.id <> T2.id
AND DATE(T1.start_date)<=DATE(T2.enddate)
AND DATE(T1.enddate)>= DATE(T2.start_date)
GROUP BY T1.id_employee
HAVING COUNT(T1.id_employee) > 1
)
ORDER BY id_employee
<强>输出强>
id id_employee
1 A
3 A
2 B
5 B
<强>演示强>
答案 1 :(得分:0)
select aa.id
from `table` aa
where exists (select * from `table` bb
where bb.id <> aa.id and (bb.start_date between aa.start_date and aa.enddate
or bb.enddate between aa.start_date and aa.enddate or
aa.start_date between bb.start_date and bb.enddate
or aa.enddate between bb.start_date and bb.enddate))
这个检查重叠日期和不同的ID。我认为应该是你正在寻找的东西。
答案 2 :(得分:0)
您的表格显示3 id_employee即。 A,B和C.如果你想要一个基于日期范围的查询,你的问题不明确:
SELECT id_employee FROM schema.table where start_date>='2018-04-01' and end_date<='2018-04-08' group by id_employee;
答案 3 :(得分:0)
我认为最简单的方法是:
select t.*
from t
where exists (select 1
from t t2
where t2.id_employee = t.id_employee and
t2.id <> t.id and
t2.start_date < t.end_date and
t2.end_date > t.start_date
);
Here是一个SQL小提琴。
只需将范围添加到外部查询即可添加日期范围:
select t.*
from t
where exists (select 1
from t t2
where t2.id_employee = t.id_employee and
t2.id <> t.id and
t2.start_date < t.end_date and
t2.end_date > t.start_date
) and
t.start_date <= ? and
t.end_date >= ?;