I am trying to count number of overlapping events between dates in SQL. Let’s assume some dates for room reservations in a hotel. Like this:
| start | end |
|---|---|
| 14.01.2024 | 17.01.2024 |
| 15.01.2024 | 17.01.2024 |
| 17.01.2024 | 19.01.2024 |
I need to find how many rooms are booked every day (the checkout date is included). In my case it should be:
| date | No of rooms |
|---|---|
| 14.01.2024 | 1 |
| 15.01.2024 | 2 |
| 16.01.2024 | 2 |
| 17.01.2024 | 3 |
| 18.01.2024 | 1 |
| 19.01.2024 | 1 |
I can generate time series of a given range (14.01 – 19.01 in this case) and join it to the data, but I am allowed to work only with a singe table. So, what I have to work with is:
| time_series | start | end |
|---|---|---|
| 14.01.2024 | 14.01.2024 | 17.01.2024 |
| 15.01.2024 | 15.01.2024 | 17.01.2024 |
| 16.01.2024 | null | null |
| 17.01.2024 | 17.01.2024 | 19.01.2024 |
| 18.01.2024 | null | null |
| 19.01.2024 | null | null |
I am looking for a select query that will take every value of the time_series column and count rows which have this date between start and end (end is included). Is there any way to do this with a sort of common table expression?
BETWEEN start AND endin theONcondition.