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


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


表结构

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

插入以下数据:函数

sname course score
张三 语文 100
张三 数学 90
张三 英语 80
李四 语文 90
李四 数学 70
李四 英语 100

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

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


上代码:code

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


总结:

经过上面的sql语句咱们实现了行值到列名的转换,咱们借用了聚合函数来与条件分支实现了此操做,其中course='语文'为条件判断,而score为实际要展现的数据字段,若是条件不成立则输出为0,聚合函数的使用并不严谨,其实avg函数也能够是其余的聚合函数。blog

相关文章
相关标签/搜索