Kanien Notiros :
Still related to my Previous Question, have a table(tb_data) which like this
+---------+---------------------+---------------------+---------------------+---------------------+-------+
| Disease | Additional_Disease1 | Additional_Disease2 | Additional_Disease3 | Additional_Disease4 | Room |
+---------+---------------------+---------------------+---------------------+---------------------+-------+
| A01 | A03 | A02 | | | Man |
| A03 | A02 | | | | Woman |
| A03 | A05 | | | | Child |
| A03 | A05 | | | | Man |
| A02 | A05 | A01 | A03 | | UGD |
+---------+---------------------+---------------------+---------------------+---------------------+-------+
My question is how to make it like this
+---------+-------+
| Disease | Total |
+---------+-------+
| A03 | 2 |
| A02 | 1 |
| A01 | 1 |
| A05 | 1 |
+---------+-------+
Here's my code attempt
select Disease, count(*) total
from (
select Disease from tb_data
union all select Additional_Disease1 from tb_data
union all select Additional_Disease2 from tb_data
union all select Additional_Disease3 from tb_data
union all select Additional_Disease4 from tb_data
) t
where Disease is not Null
and Room = 'Man'
group by Disease
order by total desc, Disease
Which result the error
Error Code: 1054. Unknown column 'Room' in 'where clause'
Nick :
Your issue is that your derived table doesn't include the Room
column. You can either filter by Room
in the derived table:
select Disease, count(*) total
from (
select Disease from tb_data where Room = 'Man'
union all select Additional_Disease1 from tb_data where Room = 'Man'
union all select Additional_Disease2 from tb_data where Room = 'Man'
union all select Additional_Disease3 from tb_data where Room = 'Man'
union all select Additional_Disease4 from tb_data where Room = 'Man'
) t
where Disease is not Null
group by Disease
order by total desc, Disease
Or include the Room
column in the derived table:
select Disease, count(*) total
from (
select Room, Disease from tb_data
union all select Room, Additional_Disease1 from tb_data
union all select Room, Additional_Disease2 from tb_data
union all select Room, Additional_Disease3 from tb_data
union all select Room, Additional_Disease4 from tb_data
) t
where Disease is not Null
and Room = 'Man'
group by Disease
order by total desc, Disease