Consider table Address , with fields Country, State, and other data fields. I want to get all the records except for those with Country,State combination as (US, IL), (US,LA), (IND,DEL)
The query goes like
Select * from Address a
where not exists
(
select Country,State
(select 'US' as Country, 'IL' as State
union
select 'US' as Country, 'LA' as State
union
select 'IND' as Country, 'DEL' as State
) e
where e.Country != a.Country and e.State != a.state
)
How can it be easily achieved (to replace coutry,state combination of union with simple subquery)? As total data is not very large, i am least bothered about performance for now.
I know i can create table variable, add all literal combination there using insert into syntax, and use table variable for not exists, but i feel it is overkill for small requirement (not exists on 2 variables).
Looks like your query tried to do this:
select *
from Address a
where not exists (
select *
from (
select 'US' as Country, 'IL' as State union all
select 'US' as Country, 'LA' as State union all
select 'IND' as Country, 'DEL' as State
) e
where e.Country = a.Country and
e.State = a.State
)
Or you could not use a derived table and still get the same result
select *
from Address as a
where not (
a.Country = 'US' and a.State = 'IL' or
a.Country = 'US' and a.State = 'LA' or
a.Country = 'IND' and a.State = 'DEL'
)
Simply use the values directly in the query:
-- Sample data.
declare @Table as Table ( Country VarChar(6), State VarChar(6), Foo VarChar(6) );
insert into @Table ( Country, State, Foo ) values
( 'US', 'IL', 'one' ), ( 'XX', 'LA', 'two' ), ( 'IND', 'XXX', 'three' ), ( 'IND', 'DEL', 'four' );
select * from @Table;
-- Demonstrate excluding specific combinations.
select T.*
from @Table as T left outer join
( values ( 'US', 'IL' ), ( 'US', 'LA' ), ( 'IND', 'DEL' ) ) as Exclude( Country, State )
on T.Country = Exclude.Country and T.State = Exclude.State
where Exclude.Country is NULL;
or
select *
from Address a
left outer join
( select 'US' as Country, 'IL' as State
union select 'US', 'LA'
union select 'IND', 'DEL' ) as n
on a.Country = n.Country and a.State = n.State
where n.Country is NULL;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With