Mysql
 sql >> Database >  >> RDS >> Mysql

MySQL - Calcola la differenza di tempo netta tra due date e orari escludendo le interruzioni?

somma tutte le tue pause che si verificano durante i tempi, quindi sottrai al risultato della funzione timediff/time_to_sec

SELECT TIME_TO_SEC(TIMEDIFF('17:00:00', '09:00:00')) -- 28800

SELECT TIME_TO_SEC(TIMEDIFF('12:30:00', '12:00:00')) -- 1800
SELECT TIME_TO_SEC(TIMEDIFF('10:30:00', '10:15:00')) -- 900

-- 26100

Assumendo questa struttura :

CREATE TABLE work_unit (
 id INT NOT NULL,
 initial_time TIME,
 final_time TIME
)
CREATE TABLE break (
 id INT NOT NULL,
 initial_time TIME,
 final_time TIME
)
INSERT work_unit VALUES (1, '09:00:00', '17:00:00')
INSERT break VALUES (1, '10:00:00', '10:15:00')
INSERT break VALUES (2, '12:00:00', '12:30:00')

Puoi calcolarlo con la query successiva:

SELECT *, TIME_TO_SEC(TIMEDIFF(final_time, initial_time)) total_time
, (SELECT SUM(
 TIME_TO_SEC(TIMEDIFF(b.final_time, b.initial_time)))
  FROM break b 
  WHERE (b.initial_time BETWEEN work_unit.initial_time AND work_unit.final_time) OR (b.final_time BETWEEN work_unit.initial_time AND work_unit.final_time)
 ) breaks 
FROM work_unit