我需要一个SQL语句来选择不同的记录,同时比较数据库的最大或最新日期。我尝试的SQL查询:

SELECT DISTINCT fleetnumber and max(traveldate), routeid, companyid, traveldate
FROM fleetSchedule

问题是它只给出1个值(最大值)。
我要求在最大/最新日期旅行的所有不同的巴士(由FruttNo标识)。
我正在寻找结果的样本数据:
fleetnumber routeid companyid   traveldate
MSH-17E     RT17    MSH         2009-07-26
FDH-17D     RT17    FDH         2009-07-26
MSH-17F     RT17    MSH         2009-07-25
MSH-27E     RT27    MSH         2009-08-24

表am的示例使用:
fleetScheduleID companyID    routeID     travelDate fleetNumber
20                  MSH      RT17        2009-07-26     MSH-17E
19                  MSH      RT17        2009-07-26     MSH-17D
18                  MSH      RT27        2009-08-24     MSH-27E

最佳答案

SELECT fleetNumber,
       MAX(travelDate) AS travelDate,
       SUBSTRING_INDEX(GROUP_CONCAT(routeID ORDER BY travelDate DESC), ',', 1) AS routeID,
       SUBSTRING_INDEX(GROUP_CONCAT(companyID ORDER BY travelDate DESC), ',', 1) AS companyID
FROM fleetSchedule
GROUP BY fleetNumber;

08-19 19:39