面试的时候总有几个sql问题,今天说下行列互转
匆匆贴上一张表,大家用烂的学生分数表,其中sid是 tb_student 的主键作为这里的外键了,这就理解为学生name 什么的就行了:
1、首先,列转行,用到 case when then else end ,聚合函数sum 或 max
select sid,
sum(case subject when '数学' then score else 0 end) '数学',
sum(case subject when '语文' then score else 0 end) '语文'
from tb_score group by sid
或者
select sid,
max(case subject when '数学' then score else 0 end) '数学',
max(case subject when '语文' then score else 0 end) '语文'
from tb_score group by sid
结果:
2 行转列 用到 union
假设上面得到的结果就是一张表名为 tmp_table 的表,及临时表:
create temporary table tmp_table select sid,
max(case subject when '数学' then score else 0 end) '数学',
max(case subject when '语文' then score else 0 end) '语文'
from tb_score group by sid ;
select * from tmp_table;
现在看看如何实现行转列:
一步一步来
临时表无法reopen 随意直接建成普通表格吧,
create table tmp_tb select sid,
max(case subject when '数学' then score else 0 end) '数学',
max(case subject when '语文' then score else 0 end) '语文'
from tb_score group by sid ;
(select sid,'数学' as subject,数学 as 'score' from tmp_tb)
union
(select sid,'语文' as subject,语文 as 'score' from tmp_tb)
得到结果
3、 oracle 、postgresql 等等数据库有内置函数如:
本人机子新装没有oracle postgresql 网上看到有讲解的:
https://yq.aliyun.com/articles/647461?spm=a2c4e.11153940.0.0.63fc7745TWAxO6