【问题标题】:mysql age wise counts based on constraint基于约束的mysql年龄明智计数
【发布时间】:2021-07-17 06:50:10
【问题描述】:

我有一张如下表

pid patient_name age sex dm htn ckd
1 one 10 m 1 0 1
2 two 15 m 1 1 1
3 three 30 m 1 0 1
4 four 40 f 1 0 1
5 five 50 f 1 0 1
6 six 60 f 1 0 1
7 seven 70 m 1 0 1

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

ranges dm_count htn_count ckd_count
80+ 0 0 0
20-29 0 0 0
50-59 0 0 0
under 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

提前致谢。

【问题讨论】:

  • 你忘了问问题。在内部查询中选择未使用的年龄和性别没有意义;外部查询不使用它们
  • 我需要男性患者的输出计数如下@CaiusJard
  • 这不是问题
  • 我需要上表中的 dm、htn 和 ckd 的年龄明智计数(总和)你能帮忙吗?

标签: mysql group-by mysql-workbench


【解决方案1】:

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

在内部查询中选择它们并在它们上使用 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"

以相同的模式添加其他人

【讨论】:

  • 没问题。要将此问题标记为已回答,请单击答案左侧的灰色复选标记,使其变为绿色。这会改变仪表板上问题的外观,让人们知道您不再寻求答案
【解决方案2】:

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 |
+-------------+----------+-----------+-----------+

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

【讨论】:

    猜你喜欢
    • 2017-11-27
    • 1970-01-01
    • 2022-01-19
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多