sql - 计算同一列的出现次数
问题描述
我有一个表,其中有一列,例如
ID
ab123
ab321
ab123
ab321
ab321
ab555
期望的输出:
Occurrences_Once | Occurrences_greater_than_one
1 2
我想要查询,所以我可以计算 IDS 的数量而不是只出现一次然后不止一次
我知道我可以利用拥有,但不是运行 2 个查询,而是想知道在一个单一查询中执行的最佳方法
谢谢
解决方案
聚合行以计算计数,然后聚合计算的计数:
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)
。
推荐阅读
- python - 在 python 中以编程方式杀死 Windows 服务
- wcf - ClientMessageInspector 不是通过配置触发而是通过代码工作
- python - 根据数据的特征是否相交对数据进行分组
- reactjs - 用数组反应状态
- javascript - 如何编写一个接受 2 个字符串的函数,并将它们添加到相应数组的开头
- json - Python 3.x 将 Unicode 文字作为它们的值写入文件
- java - Java - 在字符串中设置字段给定字段的名称
- jetty - 当以特定顺序部署多个 servlet 时,Jetty 8.1.16 返回 404
- java - what am I missing here? Basic Java
- excel - 同时输入到 2 个单元格