简体   繁体   English

寻找连续的日子

[英]Find consecutive days absent

I have a MySql table attendance with empno and timeindate columns. 我有一个empnotimeindate列的MySql表attendance I'm having trouble getting the data of an employee with 3 consecutive days absent: 我无法连续3天获取员工的数据:

Here is my sample data: 这是我的示例数据:

==========
empno:     | timeindate

empno 1    | 2013-10-01 00:00:00
empno 2    | 2013-10-01 00:00:00
empno 1    | 2013-10-02 00:00:00
empno 2    | 2013-10-02 00:00:00
empno 2    | 2013-10-03 00:00:00
empno 2    | 2013-10-04 00:00:00
empno 2    | 2013-10-05 00:00:00
empno 1    | 2013-10-06 00:00:00
empno 2    | 2013-10-06 00:00:00
----------

Please help, I have read several posts but it didn't give me the data I need and I just got confused. 请帮忙,我读了几篇文章,但没有提供我需要的数据,我感到很困惑。 I would very much appreciate any answer. 我将不胜感激任何答案。

I would try something like this. 我会尝试这样的事情。

WITH T AS
(SELECT empno, dateintime, @row:=@row+1 rownum FROM
attendance JOIN (SELECT @row:=0) init
ORDER BY empno, timeindate)

SELECT DISTINCT t1.empno
FROM T AS t1 INNER JOIN T AS t2
ON t1.empno = t2.empno AND t1.rownum = t2.rownum + 1
WHERE TIMESTAMPDIFF(DAY, t2.dateintime, t1.dateintime) >= 3

First query orders the table by datetime and enumerates rows. 第一个查询按日期时间对表进行排序并枚举行。 Then, you join it with itself, with a shift in row number, getting neighbor datetimes in one row. 然后,将其与自身连接起来,但行号会发生变化,从而将邻居日期时间排成一行。 And then, you just look for entries with a needed difference. 然后,您只需查找具有所需差异的条目。

I'm not sure it works, but it should work like that: first query: 我不确定它是否有效,但它应该像这样工作:第一个查询:

empno:     | timeindate          | row

empno 1    | 2013-10-01 00:00:00 | 0
empno 1    | 2013-10-02 00:00:00 | 1
empno 1    | 2013-10-06 00:00:00 | 2
empno 2    | 2013-10-01 00:00:00 | 3
empno 2    | 2013-10-02 00:00:00 | 4
empno 2    | 2013-10-03 00:00:00 | 5
empno 2    | 2013-10-04 00:00:00 | 6
empno 2    | 2013-10-05 00:00:00 | 7
empno 2    | 2013-10-06 00:00:00 | 8

Second query without WHERE clause: 没有WHERE子句的第二个查询:

empno 1    | 2013-10-02 00:00:00 | 2013-10-02 00:00:00
empno 1    | 2013-10-02 00:00:00 | 2013-10-06 00:00:00
empno 2    | 2013-10-01 00:00:00 | 2013-10-02 00:00:00
empno 2    | 2013-10-02 00:00:00 | 2013-10-03 00:00:00
etc.

As you see, the WHERE will filter the second row from this result. 如您所见, WHERE将从该结果中过滤第二行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM