我有一些这样的数据:
+----+--------+-------+
| 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 |
+-------+---------+----------+-------+
我要对范围进行硬编码。
目前,我打算为每个范围运行查询,有更好的方法吗?
答案 0 :(得分: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
答案 1 :(得分:2)
尝试这样的事情:
select sum(if(height<400,1,0)) '<400', sum(if(height>=400 and height<600,1,0)) '400-600'...
克