选择不同的行并应用过滤器

时间:2014-07-26 20:38:27

标签: mysql sql distinct

有人可以帮我这张桌子吗?

col1    col2
0       1
0       1
1       0
1       1
2       0
2       1
3       1
3       1

http://sqlfiddle.com/#!2/67d076

我想从第一列中选​​择不同的值,并过滤掉第二列中具有零的值。结果应该是以下列表:[0,3]

4 个答案:

答案 0 :(得分:1)

select distinct col1 from test where 
    col1 not in (select col1 from test where col2 = 0)

答案 1 :(得分:1)

这听起来像是在寻找像这样的查询:

SELECT DISTINCT `col1`
FROM `test`
WHERE `col1` NOT IN (
  SELECT `col1`
  FROM `test`
  WHERE `col2` = 0)

或使用JOIN,如下所示:

SELECT DISTINCT a.`col1`
FROM `test` a
LEFT JOIN `test` b ON a.`col1` = b.`col1` AND b.`col2` = 0
WHERE b.`col1` IS NULL

Demonstration

答案 2 :(得分:0)

select col1
from tab
group by col1
having count(case when col2 = 0 then col2 end) = 0 -- only those where no zero exists

答案 3 :(得分:0)

select col1
from test
group by col1
having min(col2) <> 0

测试:http://sqlfiddle.com/#!2/67d076/26/0

如果col2的值低于0,您可以使用:

select col1
from test
group by col1
having group_concat(col2) not like '%,0%'
   and group_concat(col2) not like '%0,%'
   and group_concat(col2) <> '0'