I have two tables which get updated at almost the exact same time – I need to join on the datetime column.
I’ve tried this:
SELECT *
FROM A, B
WHERE ABS(DATEDIFF(second, A.Date_Time, B.Date_Time)) = (
SELECT MIN(ABS(DATEDIFF(second, A.Date_Time, B2.Date_Time)))
FROM B AS B2
)
But it tells me:
Multiple columns are specified in an aggregated expression containing an outer reference. If an expression being aggregated contains an outer reference, then that outer reference must be the only column referenced in the expression.
How can I join these tables?
How about something like (assuming SQL 2005+) :
In my solution, I’m using a common-table expression or CTE for short. In the CTE, I’m using a ranking function (
ROW_NUMBER) which calculates for each row in the CTE expression. TheROW_NUMBERfunction will return provide a sequential integer for eachDateTimevalue in table A via thePARTITION BY A.DateTimeclause ordered by the absolute value of the “closeness”A.DateTimevalue to theB.DateTimevalue. Thus, I’m ranking the “closeness” usingAbs(DateDiff(s,A.DateTime, B.DateTime)and choosing the highest rank (rank = 1, aka “closest” value) for eachA.DateTimevalue. It will not matter if there is a tie as theROW_NUMBER()function will return a unique list of numbers for eachA.DateTimevalue.