纵表、横表互转
mysql中横表和纵表的互换。
将纵表中的多行记录转化成横表中的一条记录。
1、 建表
纵表结构:
1 | create table Table_A |
横表结构
1 | create table Table_B |
2、纵表变横表
方法一:聚合函数[max或sum]配合case语句
1 | select name, |
方法二:使用pivot
1 | select * from Table_A pivot (max(score)for course in(chinese,math,english)) tmp_table; |
3、横表变纵表
方法一:union all
1 | select name,'chinese' as course,chinese as score from Table_B union all |
方法二:使用unpivot
1 | select name,course,score from Table_B |