Mysql merge count multiple column

て烟熏妆下的殇ゞ 提交于 2021-01-27 19:55:47

问题


I have a table(tb_data) which like this

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

My question is how to make it like this

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

And oh here's my failed attempt

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

I've also tried this but it didn't work, it says "Unknown column 'Disease' in 'field list' as i really don't understand what was wrong


回答1:


You can use union all to unpivot your dataset, and then aggregation:

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


来源:https://stackoverflow.com/questions/60510875/mysql-merge-count-multiple-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!