Home > Blockchain >  MySQL SELECT DISTINCT Query
MySQL SELECT DISTINCT Query

Time:03-27

I need the code below to only have the highest/most recent amount of TotalRentDays for each car, instead of repeating them until it gets down to zero. The screenshot shows that the table is outputting every time a car reaches another day rented, such as CarId 15. When I put DISTINCT into the query it only made the first entry, CarId 2, not repeat.

Current Output

SELECT DISTINCT CarId, Make, Model, (NumOfRentDays) AS TotalRentDays FROM Cars
JOIN Rents ON Cars.CarId= Rents.Cars_CarId ORDER BY TotalRentDays DESC; 

CodePudding user response:

You could use max on NumOfRentDays and then group the entire result set by carid.

Should look something like this :

SELECT CarId, Make, Model, max(NumOfRentDays) AS TotalRentDays FROM Cars
JOIN Rents ON Cars.CarId= Rents.Cars_CarId  GROUP BY CarId ORDER BY TotalRentDays DESC;
  • Related