在daterange之间选择具有重复数据的查询

ctehm74n  于 2021-06-21  发布在  Mysql
关注(0)|答案(4)|浏览(287)

我有一张table

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

我想从日期范围(从开始日期到结束日期)中选择id雇员有重复数据的位置(日期范围冲突)
我可以使用什么查询

nsc4cvqm

nsc4cvqm1#

我认为最简单的方法是:

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
             );

这是一个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 >= ?;
xa9qqrwz

xa9qqrwz2#

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

演示
http://sqlfiddle.com/#!9/f1d9c9/32号

x4shl7ld

x4shl7ld3#

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))

这个检查日期重叠和不同的身份证。我想应该是你要找的。

pu3pd22g

pu3pd22g4#

您的表格显示了3个id。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;

相关问题