MySQL 计算所有项目,总计少于其他项目

MySQL count all items, aggregate less than as others

我需要从许多 mysql 5.6 表中获取数据来创建饼图。如您所知,如果饼图代表有意义的数据,它就会很有用。但是,当您有许多无意义的数据点时,比如少于 .. 或不重要的值,饼图就会变得不清楚。我需要计算每个类别的出现次数并将不重要的计数(小于 X)汇总为其他。

目前我做一个

Select category, count(*) as total from table_name group by category.  

它为我提供了每个类别及其计数。如何获得总数超过 50 的类别和低于 50 的类别,在 "Others" 下进行汇总。谢谢,乔治。

SELECT IF(total > 50, category, 'Others') AS category, SUM(total) AS total
FROM (SELECT category, COUNT(*) AS total
      FROM table_name
      GROUP BY category) AS subquery
GROUP BY category

假设您要汇总少于 4 个条目的所有类别:

select category, count(*) as total from table_name group by category having count(*) >= 4

union

select 'others', sum(c) as total from (
  select category, count(*) c from table_name group by category having count(*) < 4
) tmp