1

我需要一条 sql 语句来选择不同的记录,同时比较数据库中的最大或最新日期。这是我的表fleetschedule。它包含fleetschedule id、companyid、route、fleetnumber、traveldate。我试过的 SQL 查询:

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

问题是它只给出 1 个值(最大值)。我需要在最大/最晚日期行驶的所有不同巴士(由车队编号标识)。我正在寻找的结果样本数据:

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

正在使用的表格样本:

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  
4

3 回答 3

1

尝试这个:

select * 
from fleetSchedule
where travelDate = ( select max(travelDate) from fleetSchedule )
于 2013-03-13T13:34:42.077 回答
1
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;
于 2013-03-13T13:36:28.893 回答
0
select fleetnumber, routeid, companyid, max(traveldate)
from fleetSchedule
group by fleetnumber, routeid, companyid

需要明确的是,以上内容将为您提供每辆不同的公共汽车及其旅行的最新日期。如果您希望在整个表格中列出最近日期行驶的不同巴士,请使用以下

select distinct fleetnumber, routeid, companyid
from fleetSchedule
where traveldate = (select max(traveldate) from fleetSchedule)
于 2013-03-13T13:33:51.217 回答