方法很基础,但是容易理解和记忆
现在有两张表
纵表
name | subject | score
-------+---------+-------
Kevin | Math | 98
Kevin | Physics | 97
Kevin | Biology | 100
Sam | Math | 95
Sam | Physics | 92
Sam | Biology | 89
横表
name | math | physics | biology
-------+------+---------+---------
Kevin | 98 | 97 | 100
Sam | 95 | 92 | 89
方法:在聚合函数中使用CASE表达式
select name, sum(case when subject = 'Math' then score else 0 end) as Math, sum(case when subject = 'Physics' then score else 0 end) as Physics, sum(case when subject = 'Biology' then score else 0 end) as Biology from rowtest group by name;
方法:先分别查询各科成绩(以math为例,在新列subject中添加科目名称math,然后math的值放入新列score),然后用union合并起来
select name, 'Math' as subject, math as score from columntest union select name, 'Physics' as subject, physics as score from columntest union select name, 'Biology' as subject, biology as score from columntest order by name;