Postgres – Fetch Exact Value When All Conditions Are Met

group bypostgresqlquery

Here are the table structure and sample data.

CREATE TABLE public.product (
                id serial NOT NULL,
                opid int4 NULL,
                opvalue int4 NULL,
                info varchar NULL,
                CONSTRAINT product_pkey PRIMARY KEY (id)
            );

INSERT INTO product (id,opid,opvalue,info) VALUES 
            (1,1,1,'s1')
            ,(2,1,1,'s2')
            ,(3,2,1,'s2')
            ,(4,1,1,'s3')
            ,(6,3,2,'s3')
            ,(5,2,1,'s3')
            ;

enter image description here

Now I want query if info value satisfied all it's condition value then it will be returned.
Ex.If I pass opid=1 and opvalue=1 then only s1 should be returned not s2 because s2 have it's different condition. s1 should be returned when I pass (opid=1 and opvalue =1) and (opid=2 and opvalue =1)

Best Answer

I think this does what you want:

select *
from product p
where opid = 1 and opvalue = 1
and not exists (
  select *
  from product x
  where x.info = p.info
  and (x.opid != p.opid or x.opvalue != p.opvalue)
);

https://dbfiddle.uk/?rdbms=postgres_12&fiddle=1efcb7a125d52c27b2c386307d37da5b