0

I have these columns on my table:

id       country     
A        Italy
A        France
A        Germany
B        Italy
B        France
C        Italy
C        France

I want to get id with contains ONLY Italy and France, so the result will becoming like this:

id  
B
C

Thanks for helping me

4 Answers 4

1

The easiest way to do this for me is to just aggregate by the id and then assert that the minimum country is France, and the maximum Italy:

SELECT id
FROM yourTable
GROUP BY id
HAVING MIN(country) = 'France' AND MAX(country) = 'Italy' AND
       COUNT(DISTINCT country) = 2;
Sign up to request clarification or add additional context in comments.

1 Comment

@Nick No, you're wrong, and my (current) answer has no such caviats.
0

you can try like below by using exists

     with cte as
(
select 'A' as id , 'Italy' as country union all
select 'A','France' union all
select 'A','Germany' union all
select 'B','Italy' union all
select 'B','France' union all
select 'C' ,'Italy' union all
select 'C','France' 

) select distinct id from cte t1
 where  exists ( select 1 from cte t2
  where t1.id=t2.id  
  having count(distinct country)=2
 )
 and country in ('France','Italy')

output

id
B
C

demo fiddle

1 Comment

This is not correct. For example, remove the last record/union in the cte and you will get an incorrect result. Right now you code would return "only Italy or France", but should return "only Italy and France"
0

A more general approach in Postgres is to use array for the comparison:

select id
from t
group by id
having array_agg(country order by country) = array['France', 'Italy'];

Here is a db<>fiddle.

Comments

0

Why don't you use this

select distinct(id) 
        from countries
        where country in ('Italy','France');

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.