一尘不染

MySQL合并计数多列

sql

我有一个像这样的表(tb_data)

+---------+---------------------+---------------------+---------------------+---------------------+ 
| Disease | Additional_Disease1 | Additional_Disease2 | Additional_Disease3 | Additional_Disease4 |
+---------+---------------------+---------------------+---------------------+---------------------+ 
| A01     | A03                 | A03                 |                     |                     |
| A03     | A02                 |                     |                     |                     |
| A03     | A05                 |                     |                     |                     |
| A03     | A05                 |                     |                     |                     |
| A02     | A05                 | A01                 | A03                 |                     | 
+---------+---------------------+---------------------+---------------------+---------------------+

我的问题是如何使它像这样

+---------+-------+ 
| Disease | Total |
+---------+-------+
| A03     | 6     |
| A05     | 3     |
| A01     | 2     |
| A02     | 2     |
+---------+-------+

哦,这是我失败的尝试

select Disease, 
count(Disease + Additional_Disease1 + Additional_Disease2 + Additional_Disease3 + Additional Disease_4) as Total
from tb_data
group by Disease
order by Disease desc

我也尝试过此操作,但是它没有用,它说“字段列表中的“未知”列“疾病”,因为我真的不明白这是什么错误


阅读 134

收藏
2021-03-08

共1个答案

一尘不染

您可以使用union all取消透视数据集,然后聚合:

select disease, count(*) total
from (
    select disease from mytable
    union all select additional_disease1 from mytable
    union all select additional_disease2 from mytable
    union all select additional_disease3 from mytable
    union all select additional_disease4 from mytable
) t
group by disease
order by total desc, disease
2021-03-08