Skip to content
Advertisement

Is there a way to calculate total breaks time in between first_check_in and last_check_out?

MySQL version is 8.0.16

I want to obtain the total break time for a given date the table is as follows:

my expected results

my query only returns columns employee_id, date, first_check_in, last_check_out

Is there a way to calculate this break time in MySQL? Thanks

UPDATED my full query with time periods for expected working and break times ranges

giving the following results:

Where type 1 is for expected working hours range and type 2 is for expected break time range

Advertisement

Answer

In your original problem, following approach can work:

View on DB Fiddle

Details:

  • In MySQL 8+, we can use Analytic/Window functions like LAG(), to compute the just previous check_out time for an employee on the same date. To get this, our partition window will be over employee, and the check_in date. Partition window will be sorted by check_in time, so that the LAG() returns the just previous entries only.
  • We can determine the break_interval in minutes, using TimeStampDiff() function between the current row’s check_in time and previous row’s check_out time.
  • Once we have determined these values for every row; we can utilize them in a Subquery (Derived Table) and do sum aggregation of break_interval for an employee on a specific date. Also, getting check_out time will require some special handling when there is no check_out in the last entry of an employee for a specific date, as you need NULL there and MAX(..) won’t return NULL.
  • You can also make the query sargeable by avoiding DATE() function on the check_in time and use Range conditions.
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement