mysql行列轉換 mysql行列轉換

2021-10-25 14:31:02 字數 1404 閱讀 6472

1.一維轉二維

上圖為成績表中資料,現希望將資料轉換為下圖。

①靜態:轉化為二維表後的列名及列數是確定不變的,本例中即course只有數學、語文、英語這三門課。

select s_name,

max(if(course="數學",score,0)) as 數學,

max(if(course='語文',score,0)) as 語文,

max(if(course='英語',score,0)) as 英語,

sum(score) as 總分

②動態:轉化為二維表後的列名及列數是可變的,本例中即course的課程數不確定。

set @sql='';

select@sql:=concat(@sql,'max(if(course=\'',course,'\',score,0)) as ',course,',')from (select distinct course from grade) as a;

set@strsql=concat('select s_name,',@sql,'sum(score)as 總分 from grade group by s_name;');

2.二維轉一維

上圖為成績表2中資料,現希望將資料轉為成績表1的資料。

select name,'數學'as course,數學 as score from grade2

union all

select name,'語文'as course,語文 as score from grade2

union all

select name,'英語'as course,英語 as score from grade2

order by name;

mysql行列轉換例子 mysql行列轉換示例

現把轉換方法列舉如下 1 縱表轉橫表 縱表結構 tablea name course grade 張三語文 張三數學 張三英語 李四語文 李四數學 橫表結構 tableb name 語文數學 英語張三 李四方法一 select name,sum case course when 語文 then gr...

MySQL 行列轉換

最近在慕課上 看mysql教程 裡面關於行轉列的教程不錯 貼上練習sql 做個記錄 簡單行轉列 select a.user name,sum b.kills from user1 a join user kills b on a.id b.user id group by user name cro...

mysql行列轉換

列轉行 利用max case when then max 聚合函式 取最大值 casecoursewhen 語文 thenscoreelse0end 判斷 as 語文 別名作為列名 select name max case when course 語文 then score end as語文,max...