MySQL中的列轉行方法

2021-09-11 02:30:15 字數 1365 閱讀 5097

資料如下:

create table test (

id int (10) not null auto_increment primary key,

name varchar(20) default null,

course varchar(20) default null,

score float default 0

);insert into test(name,course,score) values

("張三", "數學", 34),

("張三", "語文", 58),

("張三", "英語", 58),

("李四", "數學", 45),

("李四", "語文", 87),

("李四", "英語", 45),

("王五", "數學", 76),

("王五", "語文", 34),

("王五", "英語", 89);

​select * from test;

轉行之前

方法一

select name,

max(case course when '數學' then score else 0 end) as 數學,

max(case course when '語文' then score else 0 end) as 語文,

max(case course when '英語' then score else 0 end) as 英語

from test

group by name;

轉行之後 

如果此處不加max 出來的結果如下:

方法二

select name,

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

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

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

from test

group by name;

這兩種方法適用於mysql,

另外pivot 是sql server中的語句 mysql不適用。

Mysql 列轉行 例項

箱表 create table yoshop shang activity box id int 11 not null auto increment comment 編號 activity id int 11 not null comment 活動id number int 11 not null...

Mysql 採用列轉行

欄位的拆分 使用函式substring index str,delim,count str 拆分物件 delim 拆分標識 substring index 搜尋時執行區分大小寫的匹配 delim count 拆分方式 如果 count為正,則返回最終分隔符左側的所有內容 從左側開始計算 如果coun...

sql中 列轉行

列轉行,主要是通過union all max來實現。假如有下面這麼乙個表 createtableprogrectdetail progrectname nvarchar 20 工程名稱 overseasupplyint,海外 商供給數量 nativesupply int,國內 商供給數量 south...