数据库
首页 > 数据库> > Sql面试题-行转列

Sql面试题-行转列

作者:互联网

场景:

原始表数据,课程和人的维度,一门课程对应一条记录,现在需要一个人对应一条数据,这条数据包含各个课程的数据,相当于列转行

方法1, case when 函数

select userid,
sum(case `subject` when '语文' then score else 0 end) as '语文',
sum(case `subject` when '数学' then score else 0 end) as '数学',
sum(case `subject` when '英语' then score else 0 end) as '英语',
sum(case `subject` when '政治' then score else 0 end) as '政治'
from tb_score group by userid;

方法2,if函数

SELECT userid,
SUM(IF(`subject`='语文',score,0)) as '语文',
SUM(IF(`subject`='数学',score,0)) as '数学',
SUM(IF(`subject`='英语',score,0)) as '英语',
SUM(IF(`subject`='政治',score,0)) as '政治' 
FROM tb_score 
GROUP BY userid

标签:case,面试题,sum,when,else,转列,score,Sql,subject
来源: https://blog.csdn.net/qq_38316704/article/details/121894720