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

1.7k Views Asked by At

I have a dataset with a column of ids (e.g.)

ID
1
2
3
3
3
4
4
5

I want to return the count of the rows where an id only appears once. For example, from the above table the query would return count = 3 as only ID 1, 2 and 5 appear once.

2

There are 2 best solutions below

0
forpas On BEST ANSWER

This query:

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

returns all the ids that you want to count, so count them like this:

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

See the demo.

0
Gordon Linoff On

One method is two levels of aggregation

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