根据分类年龄对结果进行计数(查询MySQL)

时间:2019-10-02 02:44:11

标签: mysql sql

我有一张这样的桌子:

| Results  | Age |
|----------------|
|    HT    | 20  |
|    HT    | 22  |
|    HT    | 55  |

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

|  RangeAge  | CountResult |
|--------------------------|
|    15-19   |      0      |
|    20-44   |      2      |
|    45-54   |      0      |
|    55-60   |      1      |
|    60-..   |      0      |

2 个答案:

答案 0 :(得分:3)

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

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);

答案 1 :(得分:1)

这是您的查询;

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