I have a MySql table attendance
with empno
and timeindate
columns. I'm having trouble getting the data of an employee with 3 consecutive days absent:
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:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.