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

Nem*_*ein 6 mysql sql

冰雹,堆叠!

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

举例来说,假设我在表columm中有以下值: 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)
Run Code Online (Sandbox Code Playgroud)

等等...

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

Jos*_*ger 15

也许这就是你想要的:

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

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

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

  • @Andomar不,不是.MySQL(n/5)返回小数,即使n不是小数.需要`div` (2认同)