1

想象一下我有下表:

在此处输入图像描述

我搜索的是:

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)

我很感激任何帮助

4

3 回答 3

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
于 2013-05-16T14:39:33.287 回答
4

First one:

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

Second one:

select count(distinct id)
from mytable t1
join mytable t2 on t1.id = t2.id and t2.coly = 30
where t1.colx = 20    
于 2013-05-16T14:36:53.577 回答
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)
于 2013-05-16T14:59:27.960 回答