我想按年龄段制作图表

i want to make a chart by age group

会员table

`select age, count(*) as "the number"
from (select floor((to_char(sysdate, 'YYYY') - substr(birth, 1, 4)) / 10) * 10 as age from member) 
group by age order by age asc;`

如何获取数据

当有10的数据时

没有10的数据时

即使10组没有数据我也想打印

例如,

年龄/人数

10 / 0

20 / 4

30 / 4

40 / 0

50 / 0

60 / 3

我该怎么做?

你可以试试这个:

db<>fiddle

select grp.age, COALESCE(val."the number", 0) as "the number"
from (
    select 10 as age FROM dual UNION ALL
    select 20 FROM dual UNION ALL
    select 30 FROM dual UNION ALL
    select 40 FROM dual UNION ALL
    select 50 FROM dual UNION ALL
    select 60 FROM dual UNION ALL
    select 70 FROM dual UNION ALL
    select 80 FROM dual UNION ALL
    select 90 FROM dual UNION ALL
    select 100 FROM dual
) grp
left join (
    select age, count(*) as "the number"
    from (select floor((to_char(sysdate, 'YYYY') - substr(birth, 1, 4)) / 10) * 10 as age from member) 
    group by age 
) val ON grp.age = val.age
order by grp.age asc;

仅使用当前年份和出生年份并不总能为您提供正确的年龄。如果您想找到正确的年龄,请使用 MONTHS_BETWEEN:

select age,
       count(*) as "the number"
from   (
  select floor(MONTHS_BETWEEN(SYSDATE, birth) / 120)) * 10 as age
  from   member
) 
group by age
order by age asc;

如果您的 birth 列是字符串,则使用 TO_DATE 将其转换为 DATE(但是,实际上,您应该修复列数据类型而不是解析字符串) :

select age,
       count(*) as "the number"
from   (
  select floor(MONTHS_BETWEEN(SYSDATE, TO_DATE(birth, 'YYYY.MM.DD')) / 120)) * 10 as age
  from   member
) 
group by age
order by age asc;