我的桌子有[user_id,city_id]。
我想找出满足以下条件的用户:
-它们至少存在于N个城市中
-它们存在于至少一组给定的城市中
出于明显的原因,我们不能拥有
select user_id
from my_table
where city_id in ('A', 'B')
group by user_id
having count(city_id) > 3;
如果我使用INTERSECT进行查询,这将起作用:
(select user_id from my_table where city_id in ('A', 'B'))
INTERSECT
(select user_id from my_table group by user_id having count(city_id) > 3);
(可以使用JOIN
子句构造类似的查询)
但是,这两种解决方案都让我感到不雅,我想我应该缺少一些简洁的解决方案?
任何帮助将不胜感激。
答案 0 :(得分:2)
您可以通过聚合和having
来做到这一点。这是一种方法:
select user_id
from my_table
group by user_id
having count(*) > 3 and
count(*) filter (where city_id in ('A', 'B')) = 2;
这假设用户/城市对是唯一的。如果没有,您可以使用count(distinct)
:
select user_id
from my_table
group by user_id
having count(distinct city_id) > 3 and
count(distinct city_id) filter (where city_id in ('A', 'B')) = 2;
以上假设您同时需要'A'
和'B'
。如果您至少要其中之一:
select user_id
from my_table
group by user_id
having count(*) > 3 and
count(*) filter (where city_id in ('A', 'B')) >= 1;