SQL:查询帮助

标签 sql

我的表有 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/

相关文章:

sql - Varstring 问题

mysql - 向我解释一个 MySQL 查询

MySQL 外键和外部参照表

mysql - PostgreSQL 中的更新顺序

sql - 计算特定名称的行

.net - 使用 xslt 客户端拆分字符串

mysql - 基于json select查询更新多个表列值

php - 嵌套的Mysqli连接

mysql - 如何根据多个条件选择列?

sql-server - SQL使用什么算法?