We sometimes have this need:
This kind of display related to column values is sometimes very intuitive to the data. I will use a small demo to realize this kind of operation.
Table Structure
create table demo1(
sname varchar(20) not null comment '学员',
course varchar(10) not null comment '科目',
score float not null comment '成绩'
)
Insert the following data:
takes off | course | score |
---|---|---|
Zhang San | language | 100 |
Zhang San | math | 90 |
Zhang San | English | 80 |
Li Si | language | 90 |
Li Si | math | 70 |
Li Si | English | 100 |
MySQL provides conditional branch syntax (similar to if/else, case...)
Syntax:
1.case key when condition then result when condition then result...else key (the default is original) end
2.if(field as column = 'value', data field to be displayed, another value)
Above 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;
Results of the:
Reprint address: https://www.cnblogs.com/wxxwjef/p/14952252.html
A sql reference written by myself
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