我有一个带有名称和年龄列的简单mysql表。我需要找到年龄范围(例如,长度5),其中包含最多的记录。请注意,范围可以从任何东西(如1至5年或2至6年)。我在http://sqlfiddle.com/#!2/a65265/1为同样的人创建了一个sqlfiddle
我试过使用DIV并通过论坛搜索,但我能得到的最接近的是预定义的范围,如年龄5-10岁,10-15岁等。我需要一个更通用的解决方案,所有可能的年龄范围。
发布于 2016-11-15 19:09:06
select 5 * floor((t.age-o.offset)/5) + o.offset as from_age
,5 * (floor((t.age-o.offset)/5) + 1) + o.offset - 1 as to_age
,count(*) as cnt
from test as t
cross join ( select 0 as offset
union all select 1
union all select 2
union all select 3
union all select 4
) as o
group by o.offset
,floor((t.age-o.offset)/5)
order by cnt desc
limit 1基本的想法-
每一行重复5次,偏移量在0到4之间。
每个偏移量都会导致元素的不同分布,如下图所述:
x: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| | | | | | | | | | | | | | | | | | | |
------------- ------------- ------------- -------------
floor((x-0)/5): 0 1 2 3
x: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| | | | | | | | | | | | | | | | | | | |
- ------------- ------------- ------------- -------------
floor((x-1)/5): 0 1 2 3
x: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| | | | | | | | | | | | | | | | | | | |
---- ------------- ------------- ------------- -------------
floor((x-2)/5): 0 1 2 3
x: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| | | | | | | | | | | | | | | | | | | |
------- ------------- ------------- ------------- -------------
floor((x-3)/5): 0 1 2 3
x: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| | | | | | | | | | | | | | | | | | | |
---------- ------------- ------------- ------------- -------------
floor((x-4)/5): 0 1 2 3 https://stackoverflow.com/questions/40617497
复制相似问题