I have these 3 tables:
For each car I need to visualize the data about the last (most recent) reservation:
- the car model (Model);
- the user who reserved the car (Username);
- when it was reserved (ReservedOn);
- when it was returned (ReservedUntil).
If there is no reservation for a given car, I have to show only the car model. Other fields must be empty.
I wrote the following query:
SELECT
Reservations.CarId,
res.MostRecent,
Reservations.UserId,
Reservations.ReservedOn,
Reservations.ReservedUntil
FROM
Reservations
JOIN (
Select
Reservations.CarId,
MAX(Reservations.ReservedOn) AS 'MostRecent'
FROM
Reservations
GROUP BY
Reservations.CarId
) AS res ON res.carId = Reservations.CarId
AND res.MostRecent = Reservations.ReservedOn
This first one works but I got stuck to obtain the result that I need. How could I write complete the query?