首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >基于分类范围年龄的结果计数(查询MySQL)

问基于分类范围年龄的结果计数(查询MySQL)
EN

Stack Overflow用户
提问于 2019-10-02 10:44:11
回答 2查看 39关注 0票数 1

我有一张这样的桌子:

代码语言:javascript
复制
| Results  | Age |
|----------------|
|    HT    | 20  |
|    HT    | 22  |
|    HT    | 55  |

我如何像这样显示最新数据:

代码语言:javascript
复制
|  RangeAge  | CountResult |
|--------------------------|
|    15-19   |      0      |
|    20-44   |      2      |
|    45-54   |      0      |
|    55-60   |      1      |
|    60-..   |      0      |
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-10-02 10:45:59

您需要一个派生表,以便获得计数为零的行:

代码语言:javascript
复制
select r.range, count(t.age)
from (select '15-19' as range, 15 as lo, 19 as hi  union all
      select '20-44' as range, 20 as lo, 44 as hi  union all
      . . . 
     ) r left join
     t
     on t.age >= r.lo and t.age <= r.hi
group by r.range
order by min(r.lo);
票数 3
EN

Stack Overflow用户

发布于 2019-10-02 11:11:39

这是您的查询;

代码语言:javascript
复制
select t1.* from (
    select '15-19' as rAge, count(1) as ct from tableA where Age between 15 and 19
    union all
    select '20-24', count(1) from tableA where Age between 20 and 24
    union all
    select '45-54', count(1) from tableA where Age between 45 and 54
    union all
    select '55-60', count(1) from tableA where Age between 55 and 59
    union all
    select '60', count(1) from tableA where Age > 59) t1
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58194587

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档