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

我们有时候会有这种需求:


这种与列值相关的展示有时候非常具有数据的直观性,我将用一个小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;

执行结果:

 转载地址:https://www.cnblogs.com/wxxwjef/p/14952252.html

自己写的一个sql参考

select col1,,col2  ,
MAX(if(region_type='frontier',first_prop,'')) col3,
MAX(if(region_type='finepublic',first_prop,'')) col4,
MAX(if(region_type='cn_finepublic',first_prop,'')) col5,
MAX(if(region_type='importantinst',first_prop,'')) col6,
MAX(if(region_type='leadings',first_prop,'')) col7
from 
(select  b.name as col1,b.name_abbr as col2 , a.* 
from 
(select subject_id,region_type,group_concat(first_prop) as first_prop from search_expression_list where region_type!='keyword' group by subject_id,region_type) as a
join subject_info b
on  a.subject_id = b.id
)as c 
group by col2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值