sql行列转换

sql行列转换

列转行

列转行:sum(case when then else end) 新列名, 或 max() 新列名。二者结果一样(原因见下)
题目原表如下:
在这里插入图片描述

#记得when之后的引用加‘’
select name,
sum(case subject when 'chinese' then score else 0 end) chinese,
sum(case subject when 'math' then score else 0 end) math,
sum(case subject when 'english' then score else 0 end) english
from scores group by name;

在这里插入图片描述
**为什么一定要用sum()或max():
首先分步看过程:
一不加sum()或max(),也不加group by

select name,
(case subject when 'chinese' then score else 0 end) chinese,
(case subject when 'math' then score else 0 end) math,
(case subject when 'english' then score else 0 end) english
from scores_c 

在这里插入图片描述
二不加sum()或max(),加上group by:mysql 报错!
在这里插入图片描述
但据他人博文(链接: Mysql case when 实现行转列时为什么要用max()或者其他聚合函数. )分析,说是此时只取了groupby分组之后的第一行。见下:
在这里插入图片描述
三加上sum()或max(),加上group by:列转行成功!
原因分析:
未用聚合函数时,group by分组之后,每组的第一条被取出。不符合题意。

行转列

若行转列,则原列名合并重命名一新列,且union连接。
原表:
在这里插入图片描述

select name,'chinese' as subject,chinese as score from scores_r
union
select name,'math' as subject,math as score from scores_r
order by name,subject;

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值