首页 > 解决方案 > 计算 Postgresql 中每个年龄组的频率

问题描述

我有一个输入数据,如下所示

Person_id   Age
21352471    59
22157363    51
22741394    75
22764902    27
22771872    62

我正在尝试计算每个年龄组下的频率(患者人数),例如0-10,等11-2021-30

可以帮助我如何完成吗?

我通过在线参考尝试了以下类似的操作,但这无济于事

select
  person_id,
  count(*) filter (where age<=10) as "0-10",
  count(*) filter (where age>10 and age<=20) as "11-20",
  count(*) filter (where age>20) as "21-30"
from
  age_table
group by
  person_id;

我希望我的输出如下所示

Age_group  freq
0-10         0
11-20        0
21-30        1
31-40        0
41-50        0
51-60        2
61-70        1
71-80        1 

标签: sqlpostgresqlgroup-bysql-order-by

解决方案


你可以试试下面的 -

select case when age<=10 then "0-10"
when age>10 and age<=20 then "11-20"
when age>20 and age<=30 then "21-30" end as age_group
count(person_id) as freq
from
  age_table
group by
case when age<=10 then "0-10"
when age>10 and age<=20 then "11-20"
when age>20 and age<=30 then "21-30" end  

推荐阅读