Anda dapat melakukan sesuatu seperti ini
SELECT empno, date_created, time_in, time_out,
CASE WHEN total_hours - 8 > 0 THEN total_hours - 8 ELSE 0 END overtime
FROM
(
SELECT empno, date_created, time_in, time_out,
TIME_TO_SEC(TIMEDIFF(COALESCE(time_out, '17:00:00'),
COALESCE(time_in, '09:00:00'))) / 3600 total_hours
FROM
(
SELECT empno, date_created,
MIN(CASE WHEN status = 0 THEN time_created END) time_in,
MIN(CASE WHEN status = 1 THEN time_created END) time_out
FROM biometrics
GROUP BY empno, date_created
) a
) b
Ini SQLFiddle demo
Anda perlu memberikan nilai default nyata untuk time_in
dan time_out
untuk kasus ketika mereka NULL
. Dalam kasus ekstrim jika NULL
s disebabkan oleh fakta bahwa karyawan datang pada suatu hari dan pulang pada hari lain, nilai default tersebut mungkin 00:00:00
dan 23:59:59
masing-masing karena Anda menghitung lembur per hari kalender.
PERBARUI: jika Anda ingin overtime
untuk disajikan dalam format waktu
SELECT empno, date_created, time_in, time_out,
SEC_TO_TIME(
CASE WHEN total_sec - 28800 > 0
THEN total_sec - 28800
ELSE 0 END) overtime
FROM
(
SELECT empno, date_created, time_in, time_out,
TIME_TO_SEC(TIMEDIFF(COALESCE(time_out, '17:00:00'),
COALESCE(time_in, '09:00:00'))) total_sec
FROM
(
SELECT empno, date_created,
MIN(CASE WHEN status = 0 THEN time_created END) time_in,
MIN(CASE WHEN status = 1 THEN time_created END) time_out
FROM biometrics
GROUP BY empno, date_created
) a
) b
Ini SQLFiddle demo