Skip to content
Advertisement

Sql Join selecting records from A table and selecting matching records with a condition from B table

We have Table A and Table B, Data we need is in table A and we use table B to validate case where we have matching Ids. If ids do not match we can select it without validation, but if they match we need to check if date is in between date1 and date2. We only check records in B if they have match in A; (f.e we can neglect id=4 in table B because its not in A); And we only need data from A table.

I spent too much time to create the sql to select:

Everything from Table A that is not in the table B (ids, f.e id=1,3), and select matching records where matching records A.date is between B.date1 and B.date2 (if its matching and not in between dont select)

TABLE A
id       date          col1
1       5/08/2021    11223344
2       15/06/2021   22334411
2       15/04/2021   22223344 
3       10/11/2021   22223311

TABLE B
id       date1         date2
5       5/08/2021     5/09/2021
2       15/05/2021    15/07/2021
2       15/08/2021    15/09/2021
4       15/08/2021    15/10/2021

The result should look like this:

id       date          col1
1       5/08/2021    11223344
3       10/11/2021   22223311
2       15/06/2021   22334411

Advertisement

Answer

Because you want to keep all rows in A that meet your conditions — presumably with no duplicates — I would suggest using exists and `not exists:

select a.*
from a
where exists (select 1
              from b
              where a.id = b.id and
                    a.date between b.date1 and b.date2
             ) or
      not exists (select 1
                  from b
                  where a.id = b.id
                 );

A solution using left join could return duplicate rows, if there are multiple matching rows in b.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement