Code:
SELECT start_of_gap AS next_gap
FROM (
SELECT b1.ends_at AS start_of_gap
, b2.starts_at AS end_of_gap
, ( UNIX_TIMESTAMP(b2.starts_at) -
UNIX_TIMESTAMP(b1.ends_at) )
/ 3600.00 AS gap_length_hours
FROM bookings AS b1
LEFT OUTER
JOIN bookings AS b2
ON b2.emp_id = b2.emp_id
AND b2.starts_at =
( SELECT MIN(starts_at)
FROM bookings
WHERE emp_id = b1.emp_id
AND starts_at > b1.ends_at )
WHERE b1.emp_id = 21
) AS gap_data
WHERE start_of_gap > '2008-12-26 09:00:00'
AND gap_length_hours > 0.5
ORDER
BY next_gap LIMIT 1
this still needs tweaking for the situation that arises when the last gap is open-ended, i.e. when the LEFT OUTER JOIN returns no next booking
Bookmarks