I need a single SQL query that would satisfy the below criteria.
I have 2 tables, say Table1 with these values:
| ID | Code | Description |
|---|---|---|
| 1 | 1000 | abc |
| 2 | 1000 | pqr |
| 3 | 1000 | efg |
| 4 | 2300 | rst |
| 5 | 2300 | uvw |
| 6 | 2930 | xyz |
| 7 | 3500 | aaa |
And I have another table Table2 with these values:
| ID | FromCode | ToCode | IsExcluded |
|---|---|---|---|
| 1 | 1000 | 1000 | 0 |
| 2 | 2000 | 2999 | 0 |
| 3 | 2930 | 2930 | 1 |
I need a single query that shall give me the results like:
If exists (Select 1 From Table2 where IsExcluded = 0)
-- Get the records that match the criteria
Select *
From table1 t1
Inner Join table2 t3 on (t1.Code between t3.FromCode and t3.ToCode) and t3.IsExcluded = 0
Left Join table2 t2 on (t1.Code between t2.FromCode and t2.ToCode ) and t2.IsExcluded = 1
Where t2.ID is Null
Else
Select *
From table1 t1
Left Join table2 t2 on (t1.Code between t2.FromCode and t2.ToCode) and t2.IsExcluded = 1
Where t2.ID is Null
So, basically return rows from Table1 that have:
- all the matching rows when
IsExcluded = 0. This should be true only if rows exists inTable2with conditionisExcluded = 0, otherwise return all the rows fromTable1 - exclude those rows from
Table1whereIsExcluded = 1. Again, here also if rows exists with the conditionIsExcluded = 1, then exclude the rows that meet the condition, otherwise return all the rows. This has been taken care of using left join withIsExcluded = 1 - please note that rows may or may not exists in
Table2. If they do not exists, then return all the rows fromTable1
In other words, return the rows from Table 1 that satisfy the ranges defined in Table 2 when IsExcluded = 0, and ignore rows with condition IsExcluded = 1. If there is no condition (i.e. no rows are present in Table 2), then display all the rows from Table 1.
Any help would be greatly appreciated.
Thanks.
UNION ALL, it's really not clear what output columns you want dbfiddle.uk/0R5YFyfY