sql - 如何对低于指定值的计数结果求和?
问题描述
例如,我有一个名为 Cities 的表:
+----+----------+
| ID | City |
+----+----------+
| 1 | New York |
| 2 | Chicago |
| 3 | Seattle |
| 4 | New York |
+----+----------+
当我使用查询时:
SELECT Cities.city, Count(Cities.City) AS CitiesCount
FROM Cities
GROUP BY Cities.city;
我的结果是:
+----------+-------------+
| City | CitiesCount |
+----------+-------------+
| Chicago | 1 |
| New York | 2 |
| Seattle | 1 |
+----------+-------------+
我想要做的是将 CitiesCount = 1 的所有结果汇总到“其他”行中,如下所示
+----------+-------------+
| City | CitiesCount |
+----------+-------------+
| New York | 2 |
| Other | 2 |
+----------+-------------+
我相信我需要使用联合或子查询来做到这一点?
解决方案
您可以进行条件聚合:
select (case when cnt = 1 then 'others' else city end), sum(cnt)
from (select city, count(*) as cnt
from table t1
group by city
) t
group by (case when cnt = 1 then 'others' else city end);
推荐阅读
- linux - solc --bin "faucet.sol" 未找到
- python-3.x - Python3 OpenCV - LIBTDB 错误:数据未正确标记
- javascript - 在我的硬盘崩溃后对本机项目恢复做出反应
- maven - 尽管路径上有 maven,但无法运行程序“mvn”
- flutter - 这个类在哪里使用过?
- c# - switch while 不会循环
- mysql - 查找已重修 3 门不同课程的 ID
- r - 具有相同拟合值的回归模型在 r 中使用相等的运算符相互比较时输出 FALSE
- alfresco - 如何在 alfresco 中为非管理员用户禁用“离开站点”按钮
- python - 修改一个python包,删除它并重新安装它:为什么修改是持久的?