mysql 基于约束的年龄明智计数

mysql age wise counts based on constraint

我有一个table如下

pid patient_name 年龄 性别 dm htn ckd
1 一个 10 1 0 1
2 两个 15 1 1 1
3 三个 30 1 0 1
4 四个 40 f 1 0 1
5 五个 50 f 1 0 1
6 六个 60 f 1 0 1
7 七个 70 1 0 1

我需要男性患者的输出计数如下

范围 dm_count htn_count ckd_count
80+ 0 0 0
20-29 0 0 0
50-59 0 0 0
20 岁以下 2 1 2
30-39 1 0 1
40-49 0 0 0
70-79 1 0 1
60-69 0 0 0

下面我提到了我使用的查询

select t.ranges, count(*) as occurences from (
                            select age,
                               case when age >= '0' and age < '20' then "under 20"
                               when age >= '20' and age < '30' then "20-29"
                               when age >= '30' and age < '40' then "30-39"
                               when age >= '40' and age < '50' then "40-49"
                               when age >= '50' and age < '60' then "50-59"
                               when age >= '60' and age < '70' then "60-69"
                               when age >= '70' and age < '80' then "70-79"
                               else "80+" end as ranges,sex
                               from patient_sample where sex='M') as t
                            group by t.ranges

提前致谢。

我假设您的问题是“如何为 dm、htn 和 ckd 添加计数列?

Select 在内部查询中对它们使用 SUM 而不是在外部查询中使用 COUNT

select 
  t.ranges, 
  count(*) as occurences, 
  sum(htn) as htn_count 
  ...
from (
  select 
     htn,
     ...
     case when age >= '0' and age < '20' then "under 20"

以相同的模式添加其他人

FWIW,我可能会做这样的事情...

 SELECT FLOOR(age/10)*10 range_start
      , SUM(dm) dm_count
      , SUM(htn) htn_count 
      , SUM(ckd) ckd_count 
   FROM datable 
  WHERE sex = 'm' 
  GROUP 
     BY FLOOR(age/10)*10;
+-------------+----------+-----------+-----------+
| range_start | dm_count | htn_count | ckd_count |
+-------------+----------+-----------+-----------+
|          10 |        2 |         1 |         2 |
|          30 |        1 |         0 |         1 |
|          70 |        1 |         0 |         1 |
+-------------+----------+-----------+-----------+

...并解决应用程序代码中问题的任何剩余方面