So i have this table A:
color ID MODEL
-----------------------------
red | 10 | HONDA
blue | 10 | TOYOTA
red | 15 |
I think your expected result should just be red 15. Red 30 would not qualify because of yellow 30, which shares the same id. Check out my code:
SELECT t.id, t.color
FROM t
INNER JOIN
(SELECT id
FROM t
GROUP BY id
HAVING COUNT(*) = 1) sub
ON t.id = sub.id
WHERE color = 'red'
OR color = 'blue'
This query returns all the IDs where the COLOR is red or blue but not both.
select id , color
from your_table
where color in ('red', 'blue')
and id in (
select id
from your_table
where color in ('red', 'blue')
group by id
having count(*) = 1)
Something like this
SELECT *
FROM yourtable
WHERE id IN (SELECT id
FROM youtable
GROUP BY id
HAVING Count(case when color IN ( 'red', 'blue' ) then 1 end) = 1)
or using an anti join
select t1.color, t1.id
from
tableA t1
left outer join
tableA t2 on t2.id = t1.id and t2.color != t1.color
where
t1.color in ('red', 'blue')
and t2.color is null
Use NOT EXISTS
to find rows with matching id but different colors:
select *
from yourtable a
where a.color IN ('red', 'blue')
and not exists (
select 1
from yourtable b
where a.id = b.id
and b.color NOT IN ('red', 'blue')
)
Notes:
color
tableRemoved the previous answer. Tested this and it is working.
WITH tbl
AS (SELECT
color,
id
FROM TABLE1
WHERE color IN ('red', 'blue')
)
SELECT
t1.color,
t1.id
FROM tbl t1
LEFT JOIN tbl t2
ON t1.id = t2.id
AND t1.color <> t2.color
WHERE t1.id IS NULL
OR t2.id IS NULL