我们有时候会有这种需求:
这种与列值相关的展示有时候非常具有数据的直观性,我将用一个小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;
执行结果:
转载地址: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