Reputation: 61
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
Upvotes: 0
Views: 826
Reputation: 1270873
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
.
Upvotes: 1
Reputation: 360
An improvemed to your question, would be to add your last try at a query. But from what I understood, your problem can be solved like this:
SELECT A.ID, A.date, A.col1 FROM A
LEFT JOIN B ON A.id = B.id
WHERE (A.Date BETWEEN B.date1 AND b.date2) OR B.date1 IS NULL
Upvotes: 1