需要统计取值范围内的记录。
例如:对于集合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?如何才能做到这一点?
发布于 2013-06-12 16:55:10
您可以在客户端对这些值求和,也可以使用两个查询(可能使用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完全可以在单个查询中使用子查询或复杂的条件来编写它,但它就是不那么简单和可维护。
发布于 2013-06-12 16:51:24
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发布于 2013-06-12 17:00:48
我建议这个方案借鉴了pilsetnieks和Jayram的方案:
SELECT
COUNT(*) AS cnt,
IF (myvalue >= 40; -1; ROUND(myvalue / 10) AS range
FROM t
GROUP BY rangehttps://stackoverflow.com/questions/17061156
复制相似问题