Skip to content
Advertisement

How to expand date ranges by taking into account overlapping days in PostgreSQL?

Given the following table created in a PostgreSQL database using the following SQL statements:

The table represents the list of reservations of a Bed&Breakfast with check-in date and check-out date.

It is requested to retrieve how many rooms should be set up and available for each week. In order to reduce maintenance expenses, it is required to minimise the number of offered rooms. Additionally a ,room can always be made available the same day as the check-out date. For example, if a room is checked out on the 2021-01-08 and another one is checked in on the same day, the count of rooms that needs to available for the 2021-01-08 will be only 1, and not 2.

The result should be the following:

week number_of_rooms
1 3
2 2

My approach is the following:

Which gives the following result:

week number_of_rooms
1 4
2 3

The result is not correct because my approach doesn’t take into account the fact that a room can always be made available the same day as the check-out date. How can I improve my query to take this into account?

Moreover, is there a better way in terms of performance to achieve what I am trying to do?

Advertisement

Answer

You can do:

Result:

See running example at db<>fiddle.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement