I am wondering if it is possible in SQL to return a single row to show, using the table below as an example, only a row for id 2:
table1 ( id 2 and 4 are missing value b)
id value
1 a
1 b
1 c
1 d
2 a
2 c
2 d
3 a
3 b
3 c
3 d
4 a
4 c
4 d
i basically want to find all instances where 'b' does not exist but 'a' still does exist for any id and return a single row for that any given id. i have tried something like this, but its not working as i would want it to:
select * from table1
where not exists (select distinct value from table1 where value b)
i would like the end result to be something this, identifying the values where 'b' does not exist but 'a' does(not showing the value, is unneeded for final goal):
result table
id
2
4
SELECT id
FROM table1 t1
WHERE
value = 'a'
AND NOT EXISTS (
SELECT *
FROM table1 sub
WHERE sub.id = t1.id AND sub.value = 'b'
)
This should do the job:
select distinct id
from table1 t
where not exists (
select 1
from table1 tt
where t.id = tt.id and tt.vallue = 'b'
)
and exists (
select 1
from table1 tt
where t.id = tt.id and tt.vallue = 'a'
)
Below you have shorter form. It may perform better and distinct keyword may be unnecessary if the pair (id, value) is unique.
select distinct id
from table1 t
left join table1 tt
on t.id = tt.id and tt.value = 'b'
where t.value = 'a'
and tt.id 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