here is a working example in MySQL. I was using a simple view for this.
Let us consider a fitness with customers and employees. You need to know how many hours were spent by customers when an employee was present.
First let you prepare a testing table:
CREATE TABLE Customer
(id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
customerId int NOT NULL,
arrival datetime,
leaving datetime);
INSERT INTO Customer
(customerId, arrival, leaving)
VALUES
(1, '2018-01-01 06:00:00', '2018-01-01 14:00:00'),
(2, '2018-01-01 11:00:00', '2018-01-01 19:00:00'),
(3, '2018-01-01 20:00:00', '2018-01-02 03:00:00'),
(1, '2018-01-02 06:00:00', '2018-01-02 14:00:00'),
(2, '2018-01-02 11:00:00', '2018-01-02 19:00:00')
;
CREATE TABLE Employee
(id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
employeeId int NOT NULL,
arrival datetime,
leaving datetime)
;
INSERT INTO Employee
(employeeId, arrival, leaving)
VALUES
(1, '2018-01-01 09:00:00', '2018-01-01 12:00:00',),
(2, '2018-01-01 11:30:00', '2018-01-01 20:00:00')
;
When you have a table, let you create a view with time intersections:
CREATE OR REPLACE VIEW intersectionTimeView AS select e.employeeId,
c.customerId,
IF(c.arrival>e.arrival, c.arrival, e.arrival) AS arrivalMax,
IF(c.leaving>e.leaving, e.leaving, c.leaving) AS leavingMin
FROM Customer c, Employee e
WHERE TIMEDIFF(c.arrival,e.leaving)<=0
AND TIMEDIFF(c.leaving,e.arrival)>=0
And finally and easily you can get the hours by:
SELECT employeeId, SUM( timestampdiff(minute,arrivalMax,leavingMin)/60) as summ
FROM intersectionTimeView WHERE employeeId=2
GROUP BY employeeId