简体   繁体   中英

How to get accurate data for a date range not greater than a given one in a periodically updating data

i have a database which has some units which report in at regular intervals. I want a query where I can see units that have not logged after a certain date.

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

NOW IT SHOWS ME VEHICLES WHO ALSO HAVE LOGS AFTER "2013-01-01", BECAUSE THEY ALSO HAVE LOGS BEFORE AND AFTER THIS DATE

HOW CAN I EXCLUDE NAMES FROM BEING SHOWN WHICH ALSO HAVE DATE LOGS AFTER THAT >?

Change the distinct to group by . Then add a having clause. You are looking for the largest date being before the cutoff:

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;

Judicious use of aliases would also make your query much more readable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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