Java教程

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;

这篇关于SQL行列转换的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!