问题描述
我的桌子就像
A B
1 20
1 30
2 20
3 50
4 20
4 30
4 50
我正在编写一个传递参数20
和30
的函数,然后我必须从列A
中找出确切具有值20
,{{1 }}从B列开始。在这种情况下,应返回30
。 1
不应返回,因为它也有4
。
解决方法
这是使用group by
和having
的可移植选项:
select a
from mytable
group by a
having
sum(case when b in (20,30) then 1 else 0 end) = 2
and sum(case when b not in (20,30) then 1 else 0 end) = 0
这假定没有重复的(a,b)
。否则:
having max(case when b = 20 then 1 else 0 end) = 1
and max(case when b = 30 then 1 else 0 end) = 1
and max(case when b not in (20,30) then 1 else 0 end) = 0
如果您正在运行Postgres,我们可以使用数组:
having array_agg(b order by b) = array[10,20]
在MySQL中,我们可以使用字符串聚合:
having group_concat(b order by b) = '10,20'