首页 > 解决方案 > 计算同一列的出现次数

问题描述

我有一个表,其中有一列,例如

ID 
ab123
ab321
ab123
ab321
ab321
ab555

期望的输出:

Occurrences_Once | Occurrences_greater_than_one
       1                       2

我想要查询,所以我可以计算 IDS 的数量而不是只出现一次然后不止一次

我知道我可以利用拥有,但不是运行 2 个查询,而是想知道在一个单一查询中执行的最佳方法

谢谢

标签: sql

解决方案


聚合行以计算计数,然后聚合计算的计数:

with t(id) as (values
('ab123'),
('ab321'),
('ab123'),
('ab321'),
('ab321'),
('ab555'))

select sum(case when cnt = 1 then 1 end) as Occurrences_Once
     , sum(case when cnt > 1 then 1 end) as Occurrences_greater_than_one
from (
  select id, count(*) as cnt
  from t
  group by id
) x

在 Postgres 中,您也可以使用count(*) filter (where cnt = 1)


推荐阅读