列转行:
mysql> select * from test; +------+----------+-------+ | id | subject | score | +------+----------+-------+ | 1 | chinese | 98 | | 2 | math | 95 | | 2 | politics | 87 | | 5 | chinese | 97 | | 5 | math | 100 | | 5 | politics | 92 | +------+----------+-------+ 6 rows in set (0.00 sec) mysql> select (case id when 1 then 'first' when 2 then 'second' when 5 then 'fifth' end) grade,sum(case subject when 'chinese' then score else 0 end) chinese,sum(case subject when 'math' then score else 0 end) math,sum(case subject when 'politics' then score else 0 end) politics from test group by id; +--------+---------+------+----------+ | grade | chinese | math | politics | +--------+---------+------+----------+ | first | 98 | 0 | 0 | | second | 0 | 95 | 87 | | fifth | 97 | 100 | 92 | +--------+---------+------+----------+ 3 rows in set (0.00 sec)
行转列:
复制上面的结果到一个新表test2
mysql> create table test2 as select (case id when 1 then 'first' when 2 then 'second' when 5 then 'fifth' end) grade,sum(case subject when 'chinese' then score else 0 end) chinese,sum(case subject when 'math' then score else 0 end) math,sum(case subject when 'politics' then score else 0 end) politics from test group by id; Query OK, 3 rows affected (0.12 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> select * from test2; +--------+---------+------+----------+ | grade | chinese | math | politics | +--------+---------+------+----------+ | first | 98 | 0 | 0 | | second | 0 | 95 | 87 | | fifth | 97 | 100 | 92 | +--------+---------+------+----------+ 3 rows in set (0.00 sec)
mysql> select * from (select (case grade when 'first' then 1 when 'second' then 2 when 'fifth' then 5 end) id,'chinese' subject,chinese as score from test2 union all select (case grade when 'first' then 1 when 'second' then 2 when 'fifth' then 5 end) id,'math' subject,math as score from test2 union all select (case grade when 'first' then 1 when 'second' then 2 when 'fifth' then 5 end) id,'politics' subject,politics as score from test2 order by id) a where a.score<>0; +------+----------+-------+ | id | subject | score | +------+----------+-------+ | 1 | chinese | 98 | | 2 | math | 95 | | 2 | politics | 87 | | 5 | math | 100 | | 5 | politics | 92 | | 5 | chinese | 97 | +------+----------+-------+ 6 rows in set (0.00 sec) mysql> select * from test; +------+----------+-------+ | id | subject | score | +------+----------+-------+ | 1 | chinese | 98 | | 2 | math | 95 | | 2 | politics | 87 | | 5 | chinese | 97 | | 5 | math | 100 | | 5 | politics | 92 | +------+----------+-------+ 6 rows in set (0.00 sec)