【问题标题】:Return count of ids where occurrence is equal to 1 in SQL返回 SQL 中出现次数等于 1 的 id 计数
【发布时间】:2021-06-04 09:36:28
【问题描述】:

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

ID
1
2
3
3
3
4
4
5

我想返回一个 id 只出现一次的行数。例如,从上表中查询将返回 count = 3,因为 ID 1、2 和 5 仅出现一次。

【问题讨论】:

    标签: sql group-by count having-clause


    【解决方案1】:

    这个查询:

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

    返回您要计算的所有ids,所以像这样计算它们:

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

    请参阅demo

    【讨论】:

      【解决方案2】:

      一种方法是两级聚合

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多