SQL查询功能找出来-

问题描述

我的桌子就像

A    B
1    20
1    30
2    20
3    50
4    20
4    30
4    50

我正在编写一个传递参数2030函数,然后我必须从列A中找出确切具有值20,{{1 }}从B列开始。在这种情况下,应返回301不应返回,因为它也有4

解决方法

这是使用group byhaving的可移植选项:

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'