SQL 选择仅包含特定值的行 [英] SQL select the only rows with only a certain values in them

查看:85
本文介绍了SQL 选择仅包含特定值的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里有同样的问题:SQL select其中只有特定值的行

i have the same problem here :SQL select rows with only a certain value in them

但我发现的解决方案仅适用于给定的一个值,我的意思是我希望它适用于多个值 {2 或 +},例如:

but the solution that i have found work only for one value given, i mean that i want it to work for a number of values {2 or +}, for example :

Col 1 Col 2 Col 3
1       A     1
2       A     2
3       B     1
4       C     1
5       C     2
6       D     1 
7       C     3 

我想获取仅包含 cols3 = 1 和 cols3 =2 的所有行,(仅值 1 和 2),输出将为:给定表的A",我不想有 C,因为它有另一个值为 cols 3 != 1 或 2,链接中的解决方案只允许为一个值执行此操作,但我想将其扩展到 2 个值或以上,有人可以帮助我吗 :D

I want to get all rows that just contain cols3 = 1 and cols3 =2 ONLY , (just values 1 and 2) and the output will be : "A" for the table given, i dont want to have C because it has another values of cols 3 != of 1 or 2, The solution in the link allows doing this for just one value , but i want to extend it to 2 value or plus , can someone help me please :D

推荐答案

您可以使用条件聚合:

select col2
from yourtable
group by col2 
having sum(col3=1) > 0 
  and sum(col3=2) > 0
  and sum(col3 not in (1,2)) = 0 

  • SQL Fiddle 演示
  • 这篇关于SQL 选择仅包含特定值的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆