0

我有一个数据库,其中有一些定期报告的单位。我想要一个查询,在那里我可以看到在某个日期之后没有记录的单位。

select distinct FSS_LIVE_50.dbo.AgencyVehicle.AgencyVehicleName from FSS_LIVE_50.dbo.AgencyVehicle
inner join FSS_LIVE_50.dbo.VehicleLocation
on FSS_LIVE_50.dbo.AgencyVehicle.AgencyVehicleKey = FSS_LIVE_50.dbo.VehicleLocation.AgencyVehicleKey
where FSS_LIVE_50.dbo.VehicleLocation.GPSLocationDate < '2013-01-01'
and FSS_LIVE_50.dbo.AgencyVehicle.TermDate is NULL
order by AgencyVehicleName

现在它向我显示在“2013-01-01”之后也有日志的车辆,因为他们在此日期之前和之后也有日志

我如何排除显示之后还有日期日志的姓名>?

4

1 回答 1

1

将 更改distinctgroup by。然后添加一个having子句。您正在寻找截止日期之前的最大日期:

select FSS_LIVE_50.dbo.AgencyVehicle.AgencyVehicleName
from FSS_LIVE_50.dbo.AgencyVehicle inner join
     FSS_LIVE_50.dbo.VehicleLocation
     on FSS_LIVE_50.dbo.AgencyVehicle.AgencyVehicleKey = FSS_LIVE_50.dbo.VehicleLocation.AgencyVehicleKey
where FSS_LIVE_50.dbo.AgencyVehicle.TermDate is NULL
group by FSS_LIVE_50.dbo.AgencyVehicle.AgencyVehicleName
having MAX(FSS_LIVE_50.dbo.VehicleLocation.GPSLocationDate) < '2013-01-01'
order by AgencyVehicleName;

明智地使用别名也会使您的查询更具可读性。

于 2013-07-23T19:44:12.170 回答