MySQL中关于将列值转换为列名

我们有时候会有这种需求:
image.png
这种与列值相关的展示有时候非常具有数据的直观性,我将用一个小Demo来实现此类操作。


表结构

create table demo1(
    sname  varchar(20) not null  comment '学员',
    course varchar(10) not  null comment '科目',
    score float    not null comment '成绩'
)

 

插入如下数据:

snamecoursescore
张三 语文 100
张三 数学 90
张三 英语 80
李四 语文 90
李四 数学 70
李四 英语 100

MySQL提供了条件分支语法(类似于if/else、case...)

语法:
1.case key when 条件 then 结果 when 条件 then 结果 …else key(默认为原来的)end
2.if(作为列的字段 = '值', 要展示的数据字段,另外的值)


上代码:

select sname '姓名',
max(if(course = '语文', score,0))  '语文',
avg(case course when '数学' then score end)  '数学',
max(if(course = '英语',score,0))  '英语' 
from demo1 group by sname;

 

执行结果:

image.png

posted @ 2021-06-29 22:13  wxxwjef  阅读(3365)  评论(1编辑  收藏  举报