简体   繁体   中英

MySQL get latest 7 days reservations, grouped by NameResource

I'm tring to write a query, without a good resultset.
I would to retreive a Number of reservations in last 7 days.
Grouped by .分组。
When i'm tring to set a WHERE clause like this prenotazioni.Data >= CURDATE() - INTERVAL 7 DAY
I get only NameOfResource with reservations in latest 7 days, but not the rooms without reservations.

My Query was like that: (without WHERE the result is good)

SELECT count(*) as NReservationsFromWeek,Nomeroom FROM reservations
INNER JOIN room ON reservations.FKRoom = room.IDRoom
WHERE reservations.Data >= CURDATE() - INTERVAL 7 DAY
group by room.IDRoom

Thank you to explain me where I was wrong.

You can use a LEFT JOIN , if you want all rooms, even those with a count of 0 :

SELECT ro.IDRoom, ro.Nomeroom, COUNT(re.FKRoom) as NReservationsFromWeek,
FROM room ro LEFT JOIN
     reservations re 
     ON re.FKRoom = ro.IDRoom AND
        re.Data >= CURDATE() - INTERVAL 7 DAY
GROUP BY ro.IDRoom, ro.Nomeroom;  -- Both unaggregated keys should be in the GROUP BY

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