这是“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