MySQL - 按范围分组

时间:2013-06-12 08:40:52

标签: mysql count group-by

我需要计算值范围内的记录。

例如:对于集合1, 7, 9, 23, 33, 35, 1017

select count(myvalue) group by round(myvalue / 10)给出了类似的内容:

0-10  -> 3
10-20 -> 0
20-30 -> 1
30-40 -> 2
1010-1020 -> 1

这很好用。但是,我需要设置一个上限,以便MySQL返回40+ --> 1? 如何实现这一目标?

4 个答案:

答案 0 :(得分:12)

您可以在客户端汇总值,也可以使用两个查询(可能使用union)来获取数据,例如:

select round(myvalue / 10), count(myvalue) from table where myvalue < 40 group by round(myvalue / 10)
union
select '40+', count(myvalue) from table where myvalue >= 40

绝对有可能在带有子查询或复杂条件的单个查询中编写它,但它不会那么简单和可维护。

答案 1 :(得分:3)

select t.myvalue as [range], count(*) as [occurences]
from (
  select myvalue,
   case when myvalue >= 0 and myvalue< 10 then '0-9'
   when myvalue >= 10 and myvalue< 20 then '10-19'
   when myvalue >= 20 and myvalue< 20 then '20-29'
   when myvalue >= 30 and myvalue< 40 then '30-39'
   else '40+' end as range
 from t) t
group by t.myvalue

答案 2 :(得分:2)

我建议这个解决方案借用了pilsetnieks和Jayram的解决方案:

SELECT
    COUNT(*) AS cnt,
    IF (myvalue >= 40; -1; ROUND(myvalue / 10) AS range
FROM t
GROUP BY range

答案 3 :(得分:2)

SELECT case 
   when myvalue >= 0 and myvalue< 10 then '0-9'
   when myvalue >= 10 and myvalue< 20 then '10-19'
   when myvalue >= 20 and myvalue< 20 then '20-29'
   when myvalue >= 30 and myvalue< 40 then '30-39'
   else '40+' 
   end as range
 from t 
group by range