比较多个记录中的 2 个日期

comparison of 2 dates in multiple records

我有以下table想要比较

我必须比较每个员工的日期,如果日期范围小于 60 天,它必须提取员工。 示例:

示例下方table: http://sqlfiddle.com/#!9/b44d4e

id 员工编号 日期
1228 2 2020-06-1121:10:53
3382 2 2020-06-1112:37:04
2223 2 2020-08-17 21:10:57
4479 4 2020-08-1712:37:08
4192 4 2020-07-2912:37:08
1982 4 2020-07-2921:10:56
2627 8 2020-04-1612:37:02
474 8 2020-04-1621:10:49
1002 10 2020-05-2921:10:52
3150 10 2020-05-2912:37:04

pd: mysql 数据库

任何帮助或建议我应该如何进行查询?

一种方法是使用 exists

select * from table t1
where exists ( 
  select 1 from table t2
  where t1.idEmployee = t2.idEmployee
  and t2.Id <> t1.id 
  and abs(datediff(t2.date, t1.date)) < 60)

使用现有方法:

SELECT DISTINCT idEmployee
FROM yourTable t1
WHERE EXISTS (SELECT 1 FROM yourTable t2
              WHERE t2.idEmployee = t1.idEmployee AND
                    DATEDIFF(t2.date, t1.date) > 60);

用简单的英语来说,上述查询针对 return 任何员工记录,我们可以找到相隔 60 天以上的同一员工的另一条记录。 distinct select 删除重复项。

您可以使用自连接

SELECT DISTINCT a.idEmployee
FROM employees AS a
JOIN employees AS b ON a.idEmployee = b.idEmployee AND DATEDIFF(a.date, b.date) > 60

但是,您实际上只需要将最极端的日期相互比较,而不是全部与全部进行比较。如果它们相隔少于 60 天,则所有其他日期也必须更短。

SELECT idEmployee
FROM employees
GROUP BY idEmployee
HAVING DATEDIFF(MAX(a.date), MIN(a.date)) > 60