Question : Access subquery returning multiple records even when 'select top 1' is used

Hi,

I've got a query with a subquery:

(SELECT Top 1 a.boatEnvID from boatEnvData a, boatSightings b where b.boatsightingsID = boatSightings.boatsightingsID order BY abs(boatSightings.sightTime - a.envTime)) AS envID

The subquery works to get the ID of records with the closest time. The time is calculated by subtracting two time fields and ordering the records by the lowest difference i.e. the closest time.

The subquery does not seem to want to 'select top 1' i.e. return one record, even through it is stated!   I would use first() but I would need to then use an aggregate function on the:
ORDER BY abs(boatSightings.sightTime - a.envTime) which means the subquery returns the wrong result.

The subquery is included in the full query below

Any ideas?

SELECT funcGetInitials(survey.peopleID) AS Effort_ID, funcGetInitials(survey.enteredBy) AS Input_by, BoatDetails.BoatName, survey.surveyDate AS [Date], boatTransects.TransectNumber AS transNum, boatTransects.s_latDeg, boatTransects.s_latMinSec, boatTransects.s_longDeg, boatTransects.s_longMinSec, boatTransects.e_latDeg, boatTransects.e_latMinSec, boatTransects.e_longDeg, boatTransects.eLongMinSec, boatSightings.sightTime, Species.acronym AS species, boatSightings.Adults AS No_Ad, boatSightings.Juveniles AS No_Juv, boatSightings.Calves AS No_Cal, boatSightings.[P/S], boatSightings.sightingLatDeg, boatSightings.sightingLatMinSec, boatSightings.sightingLongDeg, boatSightings.sightingLongMinSec, boatSightings.dist AS Distance, boatSightings.bearing, boatSightings.behaviour, boatSightings.Association, boatSightings.Notes,

(SELECT Top 1 a.boatEnvID from boatEnvData a, boatSightings b where b.boatsightingsID = boatSightings.boatsightingsID order BY abs(boatSightings.sightTime - a.envTime)) AS envID

FROM survey INNER JOIN (Species INNER JOIN ((BoatDetails INNER JOIN boatTransects ON BoatDetails.BoatID = boatTransects.boatID) INNER JOIN boatSightings ON boatTransects.TransectID = boatSightings.transectID) ON Species.SpeciesID = boatSightings.SpeciesID) ON survey.surveyID = boatTransects.surveyID;

Answer : Access subquery returning multiple records even when 'select top 1' is used

why would you select sightings where the sighting ID matches the sighting ID ?

where b.boatsightingsID = boatSightings.boatsightingsID
Random Solutions  
 
programming4us programming4us