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

时间:2015-05-06 20:53:09

标签: mysql pie-chart summarization

我需要从许多mysql 5.6表中获取数据以创建饼图。如您所知,如果饼图表示有意义的数据,则它非常有用。但是,如果您有许多无意义的数据点,例如小于..或非重要值,则饼图变得不清楚。我需要计算每个类别的出现次数,并将不重要的计数(小于X)汇总为OTHERS。

目前我做了一个

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

它给了我每个类别和它的数量。如何获得总数超过50的类别和下面的类别,总结在"其他"。谢谢你,乔治。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

假设您要汇总少于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