I'm trying to join two tables and filter join results but I couldn't manage it and I'd appreciate any help.
I have these row sets:
Table A
id | userid | targetid | start_date
-----------------------------------
11 | user1 | 123 | 22/10/2019
22 | user1 | 123 | 02/10/2019
33 | user1 | 123 | 04/10/2019
44 | user1 | 456 | 02/10/2019
55 | user1 | 123 | 13/11/2020
Table B
id | targetid | start_date
---------------------------
66 | 123 | 21/10/2019
77 | 456 | 11/11/2020
88 | 123 | 11/11/2020
99 | 123 | 12/11/2020
What I'm trying to do is to find most recent Table B row for each Table A row using targetid
as FK and using start_date
as filter/order values. Here's the result I'm looking for:
11 | user1 | 123 | 66
22 | user1 | 123 | 66
33 | user1 | 123 | 66
44 | user1 | 456 | 77
55 | user1 | 123 | 99
I tried to inner join and limit join condition using on ... and a.start_date <= b.start_date
but that made Table A | 55 join with each row in Table B.
This could be any type of SQL, join/cursor/loop the method and performance doesn't matter.
SELECT
that you tried. A table of expected results would also be nice.targetid
is not unique in tableb
- what date must be taken fora.start_date <= b.start_date
condition?id = 11
from Table A should map toid = 99
from Table B, not 66. So by "most recent do you mean: 1. minimum date greater than or equal to or 2. Date separated by the fewest days?