I have a query where I need a correlated subquery inside a join. I say need, what I mean is that I think I need it there… How can I do this? My query is below, I get the “The multi-part identifier “FIELDNAME GOES HERE” could not be bound” error… How can I change this query to work?
SELECT FireEvent.ExerciseID,
FireEvent.FireEventID,
tempHitEvent.HitEventID,
FireEvent.AssociatedPlayerID,
tempHitEvent.AssociatedPlayerID,
FireEvent.EventTime,
tempHitEvent.EventTime,
FireEvent.Longitude,
FireEvent.Latitude,
tempHitEvent.Longitude,
tempHitEvent.Latitude,
tempHitEvent.HitResult,
FireEvent.AmmunitionCode,
FireEvent.AmmunitionSource,
FireEvent.FireEventID,
0 AS 'IsArtillery'
FROM FireEvent
LEFT JOIN (SELECT HitEvent.*,
FireEvent.FireEventID,
Rank()
OVER (
ORDER BY HitEvent.EventTime) AS RankValue
FROM HitEvent
WHERE FireEvent.EventTime BETWEEN
Dateadd(millisecond, -5000,
HitEvent.EventTime) AND
Dateadd(millisecond,
5000, HitEvent.EventTime) AND HitEvent.FiringPlayerID = FireEvent.PlayerID
AND HitEvent.AmmunitionCode =
FireEvent.AmmunitionCode
AND HitEvent.ExerciseID =
'D289D508-1479-4C17-988C-5F6A847AE51E'
AND FireEvent.ExerciseID =
'D289D508-1479-4C17-988C-5F6A847AE51E'
AND HitEvent.HitResult NOT IN ( 0, 1 ) ) AS
tempHitEvent
ON (
RankValue = 1
AND tempHitEvent.FireEventID =
FireEvent.FireEventID
)
WHERE FireEvent.ExerciseID = 'D289D508-1479-4C17-988C-5F6A847AE51E'
ORDER BY HitEventID
Use OUTER APPLY instead of LEFT JOIN. I have had to move some of your clauses around, but the below should produce the desired result
If you only want to return results where there is a matching HitEvent use
CROSS APPLY.CROSS APPLYis toOUTER APPLYwhatINNER JOINis toLEFT JOIN.ADDENDUM
This can all be achieved using joins with no need for
OUTER APPLY, by moving not using a subquery to join HitEvent, then performing theRANKfunction on all data, not just the HitEvent table. This all needs to be moved to a subquery so the result of theRANKfunction can be inlcuded in aWHEREclause.This may offer slightly improved performance compared to using
OUTER APPLY, it may not. It depends on your schema and the amount of data you are processing. There is no substitute for testing: