I have a sqlite query that I\'m trying to write. I have two tables:
TableA (sales): id sales date
TableB (goals): id goal date
I\'m selecting from Ta
SELECT a.id, a.sales, a.date, (SELECT TOP 1 Goal
FROM TableB b WHERE b.date < a.date
ORDER BY b.date DESC) As Goal
FROM TableA a
Going off the nearest date in the past.
"Exactly equal date" would be a join on the date field. (As in Ash's answer)
"Nearest date" should probably read something like "nearest date in the future" or "nearest date in the past" (or maybe not). In this case you can use a subquery with a WHERE statement comparing the dates (< or >)
If "nearest date" is both in past and present, I'd probably code it by writing a stored procedure which creates a helper table containing the most relevant 'near date' (From B) for every date in table A. This way I'd have more control over the behaviour of the procedure and it'd be easier to change in the future.
Optimization for performance can always happen later.
Just get the cartesian product and then filter out uninteresting rows. Basically:
select a.*, b.*
from a, b
where
not exists (
select null
from b b2
where abs(b2.date - a.date) < abs(b.date - a.date)
)
I don't know if SQLite supports that, tough.