我的表有 3 个字段:id 和 unit。我想计算有多少个 ID 小于 10、10-49、50-100 等单位。最终结果应如下所示:
Category | countIds
<10 | 1516
10 - 49 | 710
50 - 99 | 632
etc.
这是返回每个 id 及其有多少个单位的查询:
select id, count(unit) as numUnits
from myTable
group by id
如何在该查询的基础上为我提供类别 countIds 结果?
注意:我不知道如何命名这个问题。请随时编辑它/提供建议
最佳答案
select category_bucket, count(*)
from (select case when category < 10 then "<10"
when category >= 10 and category <= 49 then "10 - 49"
when category >= 50 and category <= 99 then "50 - 99"
else "100+"
end category_bucket, num_units
from my_table)
group by category_bucket
动态分组的解决方案要困难得多。
关于SQL:查询帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3320569/