Mysql 列转行

列转行

原表
原表

结果表
结果表

sql语句

select 
max(case when subject='Math' then score else 0 end) as Math,
max(case when subject='Chinese' then score else 0 end) as Chinese,
max(case when subject='English' then score else 0 end) as English
from Subject

或者可以使用if(a,b,c)表达式

select 
max(if(subject='Math',score,0)) as Math,
max(if(subject='Chinese',score,0)) as Chinese,
max(if(subject='English',score,0)) as English
from Subject

解释
用case when then end 找出Math的Score,该语句会对每行数据进行判断,除了符合when条件的结果,还会包含不符合的,即为null或者设置的值。加max()的作用就是在符合和不符合的条线中区分出符合的条件,本例中就是得到各学科对应的分数,max()可以根据情况转换为其他的函数。

用到的函数:

case a when '1' then '是' else '否' then as b
当a 的值为1时,取 '是' 作为b的值,反之,取 '否'作为b的值
另一中写法:
case  when a='1' then '是' else '否' then as b

if(a,b,c)
如果a表达式为true,则结果为b,反之为c

ifnull(a,b)
如果a表达式值不为空,则返回a,为空返回b
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值