我的桌子上有这些列:
id country
A Italy
A France
A Germany
B Italy
B France
C Italy
C France
我想获取 id ,其中包含 ONLY 意大利和法国,因此结果将变成这样:
id
B
C
感谢您的帮助
答案 0 :(得分:1)
对我而言,最简单的方法是通过id
进行汇总,然后断言最小的国家是法国,最大的国家是意大利:
SELECT id
FROM yourTable
GROUP BY id
HAVING MIN(country) = 'France' AND MAX(country) = 'Italy' AND
COUNT(DISTINCT country) = 2;
答案 1 :(得分:0)
您可以使用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')
输出
id
B
C
答案 2 :(得分:0)
Postgres中更通用的方法是使用数组进行比较:
select id
from t
group by id
having array_agg(country order by country) = array['France', 'Italy'];
Here是db <>小提琴。
答案 3 :(得分:0)
你为什么不使用这个
select distinct(id)
from countries
where country in ('Italy','France');