MySQL中關於將列值轉換為列名


我們有時候會有這種需求:
image.png
這種與列值相關的展示有時候非常具有數據的直觀性,我將用一個小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;

 

執行結果:

image.png


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM