Return 在 SQL 中出现等于 1 的 ID 计数

Return count of ids where occurrence is equal to 1 in SQL

我有一个包含一列 ID 的数据集(例如)

ID
1
2
3
3
3
4
4
5

我想return id 只出现一次的行数。例如,从上面的 table 查询将 return count = 3 因为只有 ID 1、2 和 5 出现一次。

一种方法是两级聚合

select count(*)
from (select id, count(*) as cnt
      from t
      group by id
     ) i
where cnt = 1;

这个查询:

SELECT id
FROM tablename
GROUP BY id
HAVING COUNT(*) = 1

returns 所有你想数的 id,所以这样数:

SELECT COUNT(*)
FROM (
  SELECT id
  FROM tablename
  GROUP BY id
  HAVING COUNT(*) = 1
) t

参见demo