I have been struggling a bit with a query and I'm not sure if its possible in pure sql or needs to be backed by php.
Basically I want to generate an order report listing the products that have been overbooked in the system.
Table structure:
orders
id int
bookingStart DATETIME
bookingEnd DATETIME
order_lines
id int
qty int
product_id int
booking_id int
products
id int
stock int
An order can contain multiple lines with the same product. So there needs to be a SUM for each product on an order. Does anyone have any suggestions for the best way to accomplish this?
I have tried looping in a specific time interval with a subquery, but it does not take into account the overlap between different bookings and im kinda stuck here, if it can be done with a single query:
SELECT (SELECT SUM(lin2.qty) FROM booking_lines lin2,orders b2
WHERE
lin2.product_id=e.id AND
b2.id=lin2.booking_id AND (
(b2.bookingStart BETWEEN b1.bookingStart AND b1.bookingEnd) OR
(b2.bookingEnd BETWEEN b1.bookingStart AND b1.bookingEnd) OR
(b2.bookingStart < b1.bookingStart AND b2.bookingEnd > b1.bookingEnd)
) as booked SUM(lin1.qty)
FROM orders b1
LEFT JOIN order_lines lin1 ON b1.id=lin1.booking_id
LEFT JOIN products e ON e.id=lin1.product_id
(
(b1.bookingStart BETWEEN '$s' AND '$e') OR
(b1.bookingEnd BETWEEN '$s' AND '$e') OR
(b1.bookingStart < '$s' AND b1.bookingEnd > '$e')
)
GROUP BY b1.id,lin1.product_id
The problem If we have product x with a stock of 10.
Order 1 has booked 3 product x Order 2 has booked 5 product x Order 3 has booked 8 product x
The lines below indicate the booked timespan
______Order 1 x:3____
___Order 2 x:5_____
__________Order 3 x:8______
__order 4 x:2_
So its only when the 3 orders overlap that product x is actually overbooked, what i cant figure out is how to create a query capable of detecting that.