列到行的转置

Transpose of column to row

SELECT
   -- '<=19'AS Age_Range,
   case when gender = 1 then 'male'
   when gender = 2 then 'female' 
   end as gender_cat,
SUM(CASE WHEN hypertension= '1' THEN 1 ELSE 0 END) AS hypertension,
SUM(CASE WHEN chronic_cardiac_disease= '1' THEN 1 ELSE 0 END) AS chronic_cardiac_disease
FROM form where gender is not null
group by gender_cat

输出为 Gender_Cat |高血压| chronic_cardiac_disease

我需要将列转置为所需输出的行:疾病 |男 |女.

如有任何帮助,我们将不胜感激!!!

如果给定的患者可能同时患有这两种疾病,那么我会推荐union all:

select 'hypertension' as disease, sum(gender = 1) as male, sum(gender = 2) as female
from form
where hypertension = 1
select 'chronic_cardiac_disease', sum(gender = 1), sum(gender = 2)
from form
where chronic_cardiac_disease = 1

在最近的 MySQL 版本中,您将使用横向连接:

select x.disease, sum(f.gender = 1) as male, sum(f.gender = 2) as female
from form f
cross join lateral (
    select 'hypertension' as disease , hypertension as flag
    union all select 'chronic_cardiac_disease', chronic_cardiac_disease
) x
where x.flag = 1
group by x.disease