如何解决SQL查询功能找出来-
我的桌子就像
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'
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。