Skip to content
Advertisement

Mysql Employee break time history with time difference

I have employee biometric log data with inoutmode flag. I am trying to get detail break time list and with time difference.

inoutmode 4 as break-out and 5 as break-in.

here’s my Desired Output

I tried my best to achieve the output. Following is my attempted query:

My MySQL version = 10.3.17-MariaDB-1-log

partially i arrived the records using case condition but 4 and 5 inoutmode should be in single line to calculate the time difference. Any idea…

Any suggestions are appreciated.

Advertisement

Answer

Here is an approach utilizing LEAD() and LAG() Window functions available in MariaDB 10.2+ and MySQL 8+.

  • When a particular’s row InOutMode mode is 4, that means it is a break_out time. Now, we use LAG() function to get the immediate previous row for that particular EmpID. Ordering is defined based on the Time. So if the immediate previous row’s InOutMode mode is 5, that implies that we have a corresponding break_in time for this break_out time, else null.
  • Similar process is followed for the row with InOutMode mode being 5. Only difference this time is that we use LEAD() function instead; because we need to get the immediate next row, and check if it is break_out or not.
  • Now, we simply need to use this result-set as a Derived Table and DISTINCT it out (because we will have duplicate rows for every case where there are break_in and break_out together). Also, in the outer query we can calculate the time difference using TimeDiff() functionality.

Following query is done for EmpID = 235 for demo purpose:

Result


View on DB Fiddle

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement