乐趣区

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


咱们有时候会有这种需要:

这种与列值相干的展现有时候十分具备数据的直观性,我将用一个小 Demo 来实现此类操作。


表构造

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(作为列的字段 = ‘ 值 ’, 要展现的数据字段, 另外的值)


上代码:

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


总结:

通过下面的 sql 语句咱们实现了行值到列名的转换,咱们借用了聚合函数来与条件分支实现了此操作,其中 course=’ 语文 ’ 为条件判断,而 score 为理论要展现的数据字段,如果条件不成立则输入为 0, 聚合函数的应用并不谨严,其实 avg 函数也能够是其余的聚合函数。

退出移动版