I am attempting to write an SQL query for a reservations system to find the earliest available rental date for an item.
Items are categorized in the database by SKU. There can be multiple copies of an item, each uniquely identified in the database by its serial number.
When searching for the earliest available rental date for an item, it doesn't matter which serial number is chosen; simply the next one available.
The database has 2 tables; "Reservations" and "Items". There is also a Calendar table of several thousand YYYY-MM-DD future dates to work with.
The Reservations table contains columns; "record_number","sku", "serial_number", "start_date", "end_date" plus customer data. This is where each reservation is recorded as it is made.
The Items table contains columns; "sku" and "serial_number". This is an inventory of all rental items in the system.
I've worked the problem for over 2 days, but my SQL knowledge isn't enough to solve this puzzle.
I've progressed as far as generating a list of dates that have at least one reservation for a particular SKU:
SELECT calendar.dt
FROM calendar
LEFT JOIN reservations ON calendar.dt >= reservations.start_date
AND calendar.dt <= reservations.end_date
WHERE reservations.sku = 'ABC123'
I can sub-query the above into a "NOT IN ..." select statement but that only accomplishes finding dates having NO reservations for a particular SKU. I need to find the first date where at least one item is available.
I have imagined joining the dates of the Calendar table with the SKUs from the Items table with the reservation numbers of the Reservation table looking for "NULL" in the reservation_record, indicating no reservation exists for that date and serial-number combination. But I have been unable to write such a query that works.
Questions are welcome.