Khushbu
Khushbu

Reputation: 315

sql select row if any one row of group by does not contain value

How do I select a row only if group by does not contain a value.

Sample data:

CREATE TABLE tbl (
    id serial NOT NULL ,
    product int4 NULL,
    family int4 NULL    
);

insert into tbl values 
(1,3,200),
(2,6,201),
(3,7,201),
(4,1,203),
(5,3,204),
(6,6,205),
(7,1,206);

http://sqlfiddle.com/#!9/744bc1/2

Find all products such that:

  1. product != 6
  2. does not belong to any family,
    • if one of the family has product 6

Upvotes: 1

Views: 450

Answers (1)

Fahmi
Fahmi

Reputation: 37473

Use correlated subquery with not exists

DEMO

select product , family
from tbl a 
  where not exists ( select 1 from tbl b where a.family=b.family and product=6)

Upvotes: 4

Related Questions