行列互转

面试的时候总有几个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

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

luning95

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值