如何选择按范围分组的值的计数

时间:2011-02-27 21:51:02

标签: mysql sql

冰雹,堆叠!

我需要选择按范围分组的值的计数。

举例说明,假设我在表格中有以下值:1,2,4,5,6,8,9,11,13,16

然后,我想在5的范围内撤回它们的计数,如下所示:

From  0 to  4 there is 3 values (1,2,4)
From  5 to  9 there is 4 values (5,6,8,9)
From 10 to 14 there is 2 values (11,13)
From 15 to 19 there is 1 values (16)

等等......

如何在查询中进行此操作?

5 个答案:

答案 0 :(得分:14)

也许这就是你想要的:

SELECT
    5 * (n div 5) as 'from',
    5 * (n div 5) + 4 as 'to',
    COUNT(*)
FROM yourtable
GROUP BY n div 5;

对于您的示例,此查询为您提供

+------+------+----------+
| from | to   | count(*) |
+------+------+----------+
|    0 |    4 |        3 |
|    5 |    9 |        4 |
|   10 |   14 |        2 |
|   15 |   19 |        1 |
+------+------+----------+
4 rows in set (0.00 sec)

答案 1 :(得分:3)

一种方法是总和+案例方法:

select  sum(case when col1 between 0 and 4 then 1 end)
,       sum(case when col1 between 5 and 9 then 1 end)
,       sum(case when col1 between 10 and 14 then 1 end)
...
from    YourTable

另一种方法是使用范围表填充,如:

start    end
0        4
5        9
10       14

然后你可以:

select  r.start
,       r.end
,       count(case when yt.col1 between r.start and r.end then 1 end)
from    YourTable yt
cross join
        RangeTable r
group by
        r.start
,       r.end

答案 2 :(得分:2)

计算您可以分组的值。在这种情况下,您只需将值除以5即可得到该结果:

select value / 5 as Group, count(*) as Cnt
from TheTable
group by value / 5

这会给你这样的结果:

Group  Cnt
0      3
1      4
2      2
3      1

答案 3 :(得分:0)

select
val / 5 as grp,
case val / 5
when 0 then ' 0 to  5'
when 1 then ' 5 to 10'
when 2 then '10 to 15'
when 3 then '15 to 20'
end
as grpname,
count(distinct val) as cnt
from
(
select 1  as val
union select 2  
union select 4
union select 5
union select 6
union select 8
union select 9
union select 11
union select 13
union select 16
) a
group by 
val / 5

答案 4 :(得分:0)

怎么样

for(i=MIN_OF_TABLE-1;i<=MAX_OF_TABLE;$i+=RANGE){
    SELECT COUNT(`VALUE`),GROUP_CONCAT(`VALUE`) FROM `TABLE` WHERE `VALUE`>i AND `VALUE`<=i+RANGE;
}

这将获取包含您在rows =)

中显示的信息的行