Issue
I have a table with fields 'id', 'data', 'var' where id can be repeated. For example:
id data var 1 data1 a 1 data2 b 2 data3 a 3 data4 b 4 data5 a
I want get all rows, where 'var'='b' and row with the same 'id' is unique. In this example i want obtain only row with data4 and not data1 and data2 because row with data1 has 'var'='a'
Solution
You can use not in as follows:
select *
from table
where var = 'b'
and id not in (select id from table where var <> 'b')
I'm selecting in subquery all ids where it's not equals 'b', and then I'm checking the id should not equal the return id.
As you can see here:
create table test( id int, data varchar(10), var varchar(10) ); insert into test(id,data,var) values (1, 'data1', 'a'), (1, 'data2', 'b'), (2, 'data3', 'a'), (3, 'data4', 'b'), (4, 'data5', 'a'), (5, 'data5', 'b'), (5, 'data5', 'c');✓ ✓
select * from test where var = 'b' and id not in (select id from test where var <> 'b')id | data | var -: | :---- | :-- 3 | data4 | b
db<>fiddle here
Answered By - Shmiel Answer Checked By - Cary Denson (sql.easybugfix Admin)
Post a Comment
Post a Comment