I have some data,Is there a simple method?
create table tb_count(
id int not null auto_increment,
col1 enum('yes', 'no'),
col2 enum('yes', 'no'),
col3 enum('yes', 'no'),
col4 enum('yes', 'no'),
primary key(id)
) default charset=utf8;
insert into tb_count values (null, 'yes', 'yes', 'no', 'yes');
insert into tb_count values (null, 'no', 'yes', 'no', 'no');
insert into tb_count values (null, 'no', 'yes', 'no', 'yes');
insert into tb_count values (null, 'no', 'no', 'no', 'no');
select * from tb_count;
# I want to get the following output:
# value col1 col2 col3 col4
# yes 1 3 0 2
# no 3 1 4 2
By the way,I have a more complicated method, I don't want to use union all
My code
SELECT
'yes' AS 'value',
SUM( CASE WHEN col1 = 'yes' THEN 1 ELSE 0 END ) AS col1,
SUM( CASE WHEN col2 = 'yes' THEN 1 ELSE 0 END ) AS col2,
SUM( CASE WHEN col3 = 'yes' THEN 1 ELSE 0 END ) AS col3,
SUM( CASE WHEN col4 = 'yes' THEN 1 ELSE 0 END ) AS col4
FROM
tb_count
UNION ALL
SELECT
'no' AS 'value',
SUM( CASE WHEN col1 = 'no' THEN 1 ELSE 0 END ) AS col1,
SUM( CASE WHEN col2 = 'no' THEN 1 ELSE 0 END ) AS col2,
SUM( CASE WHEN col3 = 'no' THEN 1 ELSE 0 END ) AS col3,
SUM( CASE WHEN col4 = 'no' THEN 1 ELSE 0 END ) AS col4
FROM
tb_count
I Wanted to know if it's good practice to do that and what would be the best way to do that?