SQL:行列转换

方法很基础,但是容易理解和记忆

现在有两张表

纵表

 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 null end) as Math,
sum(case when subject = 'Physics' then score else null end) as Physics,
sum(case when subject = 'Biology' then score else null 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;

SQL:行列转换_第1张图片

你可能感兴趣的:(SQL,sql)