Mysql 合并计数多列

Mysql merge count multiple column

我有一个像这样的table(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

我也试过 this 但它没有用,它说“'field list' 中的未知列 'Disease' 因为我真的不明白哪里出了问题

您可以使用 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