1

我有一些这样的数据:

+----+--------+-------+
| 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 |
+-------+---------+----------+-------+

我将对范围进行硬编码。

目前,我计划对每个范围进行查询,有没有更好的方法?

4

2 回答 2

3
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
于 2012-04-15T13:25:05.137 回答
2

尝试这样的事情:

select sum(if(height<400,1,0)) '<400', sum(if(height>=400 and height<600,1,0)) '400-600'...

G

于 2012-04-15T13:26:38.840 回答