我正在使用 COUNT(*) 来计算列中具有不同值的项目数。
我用过这个查询:
SELECT `type`, COUNT(*) FROM `fruits` GROUP BY `type`
status
是一列,其中的值为“Apples”、“Oranges”、“Grapes”、“Bananas”
所以结果是:
+------------+---------+
| Type | COUNT(*)|
+------------+---------+
| Apples | 30|
| Oranges | 8|
| Bananas | 6|
| Grapes | 2|
+------------+---------+
但我只想计算“Apples”和“Oranges”。其余的放在一行中。像这样:
+------------+---------+
| Type | COUNT(*)|
+------------+---------+
| Apples | 30|
| Oranges | 8|
| Others | 8|
+------------+---------+
有办法吗?
最佳答案
在派生表 中使用case
表达式 将其他表分组在一起。然后汇总其结果:
select `type`, COUNT(*)
from
(
SELECT case when `type` in ('Apples','Oranges') then `type`
else 'Others'
end as 'type'
FROM `fruits`
) dt
GROUP BY `type`
这样您只需编写一次 case 表达式,即不易出错且更易于维护。
关于mysql - 如何收集不需要的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57603497/