SQL select the only rows with only a certain values in them

萝らか妹 提交于 2019-12-12 03:46:50

问题


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

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 

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


回答1:


You can use conditional aggregation for this:

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 Demo



回答2:


SELECT col 2 FROM TABLE WHERE (col 3 =1 OR col 3 =2) AND col 2 NOT IN (SELECT col 2 FROM TABLE WHERE (col 3 <>2 AND col 3 <> 1));



来源:https://stackoverflow.com/questions/37759228/sql-select-the-only-rows-with-only-a-certain-values-in-them

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!