mysql - 在mysql中按范围分组

标签 mysql group-by range

Table:   
new_table                                                    
user_number  | diff                  
     2       |  0                      
     1       |  28  
     2       |  32  
     1       |  40  
     1       |  53  
     1       |  59  
     1       |  101  
     1       |  105  
     2       |  108  
     2       |  129  
     2       |  130    
     1       |  144  


            |(result)
            v

range  | number of users  
0-20   |  2  
21-41  |  3  
42-62  |  1  
63-83  |  2  
84-104 |  1  
105-135|  0  
136-156|  3


select t.range as [range], count(*) as [number of users]  
from (  
  select case    
    when diff between 0 and 20 then ' 0-20'  
    when diff between 21 and 41 then ' 21-41'  
    when diff between 42 and 62 then ' 42-62'  
    when diff between 63 and 83 then ' 63-83'  
    when diff between 84 and 104 then ' 84-104'  
    when diff between 105 and 135 then ' 105-135'  
    else '136-156'   
     end as range  
  from new_table) t  
group by t.diff  

Error:

You have an error in your SQL syntax, near '[range], count(*) as [number of users]  
from (  
  select case  
    when' at line 1  

最佳答案

这是按范围分组的通用代码,因为执行 case 语句会变得非常麻烦。

“floor”函数可用于查找范围的底部(不是 Bohemian 使用的“round”),并添加数量(下例中为 19)以查找范围的顶部。请记住不要与范围的底部和顶部重叠!

mysql> create table new_table (user_number int, diff int);
Query OK, 0 rows affected (0.14 sec)

mysql>  insert into new_table values (2, 0), (1, 28), (2, 32), (1, 40), (1, 53),
        (1, 59), (1, 101), (1, 105), (2, 108), (2, 129), (2, 130), (1, 144);
Query OK, 12 rows affected (0.01 sec)
Records: 12  Duplicates: 0  Warnings: 0

mysql> select concat(21*floor(diff/21), '-', 21*floor(diff/21) + 20) as `range`,
       count(*) as `number of users` from new_table group by 1 order by diff;
+---------+-----------------+
| range   | number of users |
+---------+-----------------+
| 0-20    |               1 |
| 21-41   |               3 |
| 42-62   |               2 |
| 84-104  |               1 |
| 105-125 |               2 |
| 126-146 |               3 |
+---------+-----------------+
6 rows in set (0.01 sec)

关于mysql - 在mysql中按范围分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6687534/

相关文章:

php - 使用准备好的语句 PHP 返回 MySQL 错误代码和自定义响应

javascript - 如何进行跨越多个元素的范围选择?

php - 测试一个范围是否与另一个数字范围相交

php - 如何查询 MySQL 数据库以确定用户是否连续登录 30 天还是 100 天?

php - 输入值取决于数据库中下拉列表的值

mysql - 如何从另一个表中引用 SQL?

来自 2 个表的 MySQL COUNT

mysql - 子查询 : slow. 中的 GROUP BY 使用 View 有帮助,但这可以在一个查询中完成吗?

mysql - 选择最近的值与其中

excel - 如何在excel VBA中为具有命名范围的图表设置源数据