简体   繁体   中英

Get total amount of days for the month between 2 dates grouped by month

I have a booking system for hotel rooms, sometimes there are reservations that start in one month and finish in another month. For example 22 April 2019 to 07 May 2019.

I need to be able to see how many days the room was booked in April.

Can't figure out how to reduce the overlapping days in the next month.

So if I have those bookings:

07/Apr/2019 to 12/Apr/2019
22/Apr/2019 to 07/May/2019
29/May/2019 to 03/June/2019

It should give me:

April 2019: 13 Days May 2019: 10 Days June 2019: 3 Days

I tried using DATEDIFF and SUM but it adds MAY Dates also.


$sql = "SELECT 
id, SUM(DATEDIFF(booking_to, transaction_date)) + 1 AS occup,
COALESCE(COUNT(id), 0) AS `transactions`,
COALESCE(SUM(revenue), 0) AS `revenue`
FROM transactions
WHERE property_id = $pvid
AND MONTH(transaction_date) = $tranmonth 
AND YEAR(transaction_date) = $tranyear
group by property_id"; 

Currently it is giving me 20 Days which is incorrect.

Is it possible to the amount of days booked only for April?

what you probably need is the last day of the month and diff it after

SELECT LAST_DAY(NOW());

edit:

     select now() as now, timestampdiff(day, now(), last_day(now())) as diff;
+---------------------+------+
| now                 | diff |
+---------------------+------+
| 2019-05-04 05:48:43 |   26 |
+---------------------+------+
1 row in set (0.00 sec)

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