数据库
首页 > 数据库> > SQL行列转换

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 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;

标签:Biology,转换,name,行列,score,math,SQL,Math,subject
来源: https://blog.csdn.net/m0_59044674/article/details/118703804