0

I have two tables as shown in the image. I want to create a SQL query in postgresql to get the pkey and minimum count for each unique 'pkey' in table 1 where 'name1' is not present in the array of column 'name' in table 2. 'name' is a array enter image description here

1
  • 1
    Good question, but you'd make it easier for people by providing text, not images. Ideal would be CREATE TABLE and INSERT statements. Commented Feb 25, 2018 at 11:13

1 Answer 1

1

You can use ANY to check if one element exists in your name's array.

create table t1 (pkey int, cnt int);
create table t2 (pkey int, name text[]);

insert into t1 values (1, 11),(1, 9),(2, 14),(2, 15),(3, 21),(3,16);
insert into t2 values
(1, array['name1','name2']),
(1, array['name3','name2']),
(2, array['name4','name1']),
(2, array['name5','name2']),
(3, array['name2','name3']),
(3, array['name4','name5']);
select pkey
from   t2
where 'name1' = any(name);
| pkey |
| ---: |
|    1 |
|    2 |
select   t1.pkey, min(cnt) count
from     t1
where    not exists (select 1
                     from   t2
                     where  t2.pkey = t1.pkey
                     and    'name1' = any(name))
group by t1.pkey;
pkey | count
---: | ----:
   3 |    16

dbfiddle here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.