简体   繁体   中英

How to count number of nights booked per month with check-in and check-out dates having different months in SQL?

I have a dataset like the below dataset. I want to find the number of nights each id was occupied per month. For some rows, the check-in and checkout dates are in different months. I want to know how to write a query to have the occupancy per month. For example, for id=1, check-in: 2020-01-26 and checkout date: 2020-03-02. How can I have a table that shows January occupancy: 6, Feb occupancy: 29, and March occupancy: 1

id check-in checkout
1 2020-01-26 2020-03-02

first, you need a numbers table or tally table , after you can easily to it using this query :

select c.id,
    case when m.id <> 0 
        then adddate(last_day(adddate(checkin_date, interval m.id -1 month)),interval 1 day)
        else checkin_date 
    end as Checkin_date,
    case when last_day(adddate(checkin_date, interval m.id month)) > checkout_date 
        then checkout_date 
        else last_day(adddate(checkin_date, interval m.id month)) 
    end checout_date,
    datediff(case when last_day(adddate(checkin_date, interval m.id month)) > checkout_date 
                then checkout_date 
                else last_day(adddate(checkin_date, interval m.id month)) end,
             case when m.id <> 0 
                then last_day(adddate(checkin_date, interval m.id -1 month))
                else adddate(checkin_date, interval -1 day) end
            ) daysdiff
from checkins c
join numbers m on m.id <= period_diff(date_format(checkout_date, "%Y%m"),date_format(checkin_date, "%Y%m"))
order by  c.id, checkin_date

this is works for any gap (for more than 1 year)

db<>fiddle here

Requirement is very wide but I will try to assist you.

If I understand correctly, you want month-wise aggregated result of occupied inventory.

You can try below query as base query then add more criteria logic based on your need

select month(check_in), sum(dayofyear(check_out) - dayofyear(check_in)) as 'occupied_days'
from inventory 
where year(check_in)=year(check_out) 
group by 1;

Above query will work only for dataset where check_in & check_out happened within same year.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM