SQL:选择有条件的行?

时间:2013-05-16 14:32:35

标签: sql

想象一下,我有下表:

enter image description here

我搜索的是:

select count(id) where "colX is never 20 AND colY is never 31"

预期结果:

3 (= id numbers 5,7,8)

并且

select count(id) where "colX contains (at least once) 20 AND colY contains (at least once) 31"

预期结果:

1 (= id number 2)

我感谢任何帮助

3 个答案:

答案 0 :(得分:4)

第一个:

select count(distinct id)
from mytable
where id not in (select id from mytable where colX = 20 or colY = 31)

第二个:

select count(distinct id)
from mytable t1
join mytable t2 on t1.id = t2.id and t2.coly = 30
where t1.colx = 20    

答案 1 :(得分:4)

这是“sets-within-sets”子查询的示例。最好的方法是使用带有having子句的聚合,因为它是最通用的方法。这将生成此类ID的列表:

select id
from t
group by id
having SUM(case when colX = 20 then 1 else 0 end) = 0 and  -- colX is never 20
       SUM(case when colY = 31 then 1 else 0 end) = 0      -- colY is never 31

您可以使用子查询来计算数字:

select count(*)
from (select id
      from t
      group by id
      having SUM(case when colX = 20 then 1 else 0 end) = 0 and  -- colX is never 20
             SUM(case when colY = 31 then 1 else 0 end) = 0      -- colY is never 31
     ) s

对于第二种情况,您将拥有:

select count(*)
from (select id
      from t
      group by id
      having SUM(case when colX = 20 then 1 else 0 end) > 0 and  -- colX has at least one 20
             SUM(case when colY = 31 then 1 else 0 end) > 0      -- colY has at least one 31
     ) s

答案 2 :(得分:0)

你走了:

Select COUNT(distinct ID)
from Test_Table1 A
WHERE NOT EXISTS ( SELECT 1 from Test_Table1 c 
        WHERE c.id = a.id 
        AND colX =20 AND coly= 31)

Select COUNT(distinct ID)
from Test_Table1 A
WHERE EXISTS ( SELECT 1 from Test_Table1 c 
        WHERE c.id = a.id 
        AND colX =20 AND coly= 31)