I have a table with bookings:
- id (int)
- quantity (tinyint)
- date_start (timestamp)
- date_end (timestamp)
Bookings can overlap, so there can for example be 20 bookings at the same time. Now I want to do two queries:
1) Retrieve the maximum sum of quantities within a given period.
2) Retrieve the minimum sum of quantities within a given period.
I have no idea how to add the quantities of ONLY the overlapping bookings together, and not of non-overlapping bookings. Any help would be greatly appreciated.
edit: i drew a picture for clarity: https://i.stack.imgur.com/I9nvq.png
Construct a list of all booking boundaries (i.e. start and end dates) which occur in the desired period:
Add to that the boundary which occurs immediately before the desired period:
Make an outer join between this result and the
bookingstable, keeping all of the boundaries but only including a booking if it contributes to the number of simultaneous people after the boundary:Sum the number of people at each boundary:
Find the maximum and minimum:
Putting it all together:
See it on sqlfiddle.