mysql - 选择和分组范围

标签 mysql sql

我有一些这样的数据:

+----+--------+-------+
| id | height | width |
+----+--------+-------+
|  1 |   1000 |   300 |
|  2 |   1024 |   330 |
|  3 |    600 |   200 |
|  4 |    624 |   311 |
|  5 |    724 |   511 |
|  6 |    300 |   200 |
+----+--------+-------+

有更多的行。

我想运行一个执行如下操作的查询:

Count how many rows have a height between 0 and 400, between 401 and 600, between 601 and 1000, and 1000+

在这种情况下,我希望它返回如下内容:

+-------+---------+----------+-------+
| 0-400 | 401-600 | 601-1000 | 1000+ |
+-------+---------+----------+-------+
|     1 |       1 |        3 |     1 |
+-------+---------+----------+-------+

我将对范围进行硬编码。

目前,我打算对每个范围运行一个查询,有没有更好的方法?

最佳答案

select  sum(case when height between 0 and 400 then 1 end) as [0-400]
,       sum(case when height between 401 and 600 then 1 end) as [401-600]
,       ...
from    YourTable

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

相关文章:

mysql - MySQL中的AVG和STD使用同一行的字段值

php - 编辑模式下的多个复选框 : Undefined index

mysql - 如何在 MySQL 中创建此 View ?

php - "error in your SQL syntax .. near ' 键 ' "

mysql - phpMyAdmin - 无法连接 - 无效设置 - 自从我添加了 root 密码 - 被锁定

mysql - mysql中8位数字转换为日期类型

mysql - sql函数输入

mysql - 获得最快的 MySql 查询

php mysqli_query 拒绝用户访问

mysql - 1-多-多的数据库结构