简体   繁体   English

MySQL SELECT DISTINCT 查询

[英]MySQL SELECT DISTINCT Query

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.我需要下面的代码只为每辆车提供最高/最近的 TotalRentDays,而不是重复它们直到它降到零。 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.屏幕截图显示,每当汽车到达租用的另一天时,该表就会输出,例如 CarId 15。当我将 DISTINCT 放入查询中时,它只做了第一个条目,CarId 2,没有重复。

Current Output当前 Output

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

You could use max on NumOfRentDays and then group the entire result set by carid .您可以在NumOfRentDays上使用max ,然后按carid对整个结果集进行group

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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