列转行
原表
结果表
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