简体   繁体   中英

specific status on consecutive days

I have a MySQL table ATT which has EMP_ID , ATT_DATE , ATT_STATUS with ATT_STATUS with different values 1-Present,2-Absent,3-Weekly-off. I want to find out those EMP_ID 's which have status 2 consecutively for 10 days in a given date range.

Please help

Please have a try with this:

SELECT EMP_ID FROM (
SELECT
IF((@prevDate!=(q.ATT_DATE - INTERVAL 1 DAY)) OR (@prevEmp!=q.EMP_ID) OR (q.ATT_STATUS != 2), @rownum:=@rownum+1, @rownum:=@rownum) AS rownumber, @prevDate:=q.ATT_DATE, @prevEmp:=q.EMP_ID, q.*
FROM (
SELECT
EMP_ID
, ATT_DATE
, ATT_STATUS
FROM
org_tb_dailyattendance, (SELECT @rownum:=0, @prevDate:='', @prevEmp:=0) vars
WHERE ATT_DATE BETWEEN '2013-01-01' AND '2013-02-15'
ORDER BY EMP_ID, ATT_DATE, ATT_STATUS
) q
) sq
GROUP BY EMP_ID, rownumber
HAVING COUNT(*) >= 10

The logic is, to first sort the table by employee id and the dates. Then introduce a rownumber which increases only if

  • the days are not consecutive or
  • the employee id is not the previous one or
  • the status is not 2

Then I just grouped by this rownumber and counted if there are 10 rows in each group. That should be the ones who were absent for 10 days or more.

Have you tried something like this

SELECT EMP_ID count(*) as consecutive_count min(ATT_DATE)
FROM (SELECT * FROM ATT ORDER BY EMP_ID) 
GROUP BY EMP_ID, ATT_DATE
WHERE ATT_STATUS = 2
HAVING consecutive_count > 10

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.

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