我需要计算值范围内的记录。
例如:对于集合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
?如何实现?
您可以对客户端的值求和,也可以使用两个查询(可能带有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
绝对可以将它写在带有子查询或复杂条件的单个查询中,但它不会那么简单和可维护。
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
我建议这个解决方案借鉴了 pilsetnieks 和 Jayram 的解决方案:
SELECT
COUNT(*) AS cnt,
IF (myvalue >= 40; -1; ROUND(myvalue / 10) AS range
FROM t
GROUP BY range
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