Can someone help me figure out how is the best way?
I have a list of people with cars. I need to fulfill a request that will return people with a car type and not have another type at the same time.
Here is my example:
ID Name CarType
----------- ---------- ----------
1 John MINI VAN
1 John SUV
2 Mary SUV
2 Mary SEDAN
3 Paul SPORT
3 Paul TRUCK
4 Joe SUV
4 Joe MINI VAN
For example, I want to display only people who have an SUV and do not have a MINI VAN. If we try the CarType IN ("SUV") AND NOT IN ("MINI VAN") sentence, this will not work because the second statement is simply ignored.
To return people who are of type but not of another type at the same time, I tried the following:
- Create a temporary table with an IN clause, say @Contains
- Create a temporary table with a NOT IN clause, say @DoesNotContain
- @Contains, IN
- where , @DoesNotContain.
:
declare @Contains table(
ID int not null
)
declare @DoesNotContains table(
ID int not null
)
insert into @Contains
SELECT ID from @temp where CarType = 'SUV'
insert into @DoesNotContains
SELECT ID from @temp where CarType = 'MINI VAN'
SELECT
a.ID, Name
FROM
@temp a
INNER JOIN @Contains b on b.ID = a.ID
WHERE
a.ID NOT IN (SELECT ID FROM @DoesNotContains)
Group by
a.ID, Name
, , MINI VAN.
:
- IN NOT IN ? - SQL, ? (, , SQL, SQL 2005)
- ?
- , IN NOT IN JOIN?
- NOT IN JOIN?
!
, , , , . : (
, , MINI VAN, TRUCK AND NOT SEDAN. .