我想计算在列Code中有多少个不同的id值为'A'和'B'
<表类>
ID
代码
tbody><<tr>1 1B 1C 1D 2 2B 2C 表类>
如果你想计数不同的代码:
SELECT COUNT(DISTINCT ID)
FROM tab
WHERE CODE IN ('A', 'B')
GROUP BY CODE ;
如果您想要与A
或B
中的任何一个字母配对的不同ID的公共计数,使用此:
SELECT COUNT(DISTINCT ID)
FROM tab
WHERE CODE IN ('A', 'B');
我想计算
code
列中有多少个不同的id
值为'A'
和'B'
。
我推荐group by
和having
;这将为您提供具有两个代码的ids
列表(假设没有重复的id/code)。
select id
from tab
where code in ('A', 'B') -- rows that have any of the two codes
group by id
having count(*) = 2 -- both codes are present in the group
现在我们可以计算上面的查询返回了多少行来得到您想要的输出:
select count(*) as cnt
from (
select id
from tab
where code in ('A', 'B')
group by id
having count(*) = 2
) t
我希望这种方法比使用intersect
的解决方案执行得更好,因为它只扫描表一次。
请注意,也可以使用exists
,正如您在第二次尝试中所打算的那样(尽管这是一次表扫描);我们只需要修改过滤:
select count(*)
from tab as t1
where t1.code = 'A' and exists (
select 1
from tab t2
where t2.id = t1.id and t2.code = 'B'
)
选择代码A的行,并确保给定id有另一行代码b。