MySQL 行轉列 列轉行

2021-10-08 19:35:18 字數 2271 閱讀 8258

以下內容包括:行轉列、sql、執行效果展示、列轉行、sql、執行效果展示、總結、附上的建表語句

一、行轉列

廢話不多說,先上sql(兩種方式):

-- 行轉列:方法①

select

id,name,

group_concat(case when subject = '語文' then score end separator '') '語文',

group_concat(case when subject = '數學' then score end separator '') '數學',

group_concat(case when subject = '英語' then score end separator '') '英語'

from test1

group by name;

-- 行轉列:方法②

select

id,name,

sum(if(subject = '語文',score,0)) as '語文',

sum(if(subject = '數學',score,0)) as '數學',

sum(if(subject = '英語',score,0)) as '英語'

from test1

group by name;

效果如下:

這裡方法②也可以使用group_concat的方式,兩種方法的效果一樣。

二、列轉行

廢話不多說,先上sql:

-- 列轉行

select name,'語文' as subject,語文 as score from test2

union all

select name,'數學' as subject,數學 as score from test2

union all

select name,'英語' as subject,英語 as score from test2

order by name asc,subject desc;

效果如下:

總結:行轉列主要借助:case when或if,這兩種都是判斷條件,思路》當滿足某個學科的時候我們把它當做新的一列。

列轉行主要借助:union或union all,這兩個都是把結果集合並起來,思路》 每次查詢學生名稱(基本列)和學科的其中一列的值,再把它們組合起來,這樣你的結果集就是只有學生名稱和科目成績兩列了。(我這裡多加了一列科目)

附上建表語句:

create table `test1` (

`id` int(11) not null auto_increment,

`name` varchar(30) default null comment '學生名稱',

`subject` varchar(30) default null comment '科目名稱',

`score` decimal(5,1) default null comment '分數',

primary key (`id`)

) engine=innodb auto_increment=7 default charset=utf8;

create table `test2` (

`id` int(11) not null auto_increment,

`name` varchar(30) default null comment '學生名稱',

`語文` decimal(5,1) default null comment '語文科目分數',

`數學` decimal(5,1) default null comment '數學科目分數',

`英語` decimal(5,1) default null comment '英語科目分數',

primary key (`id`)

) engine=innodb auto_increment=3 default charset=utf8;

Mysql 行轉列 列轉行

create table test tb grade id int 10 not null auto increment,user name varchar 20 default null,course varchar 20 default null,score float default 0 pr...

MySQL行轉列 列轉行

max case course when 數學 then score else 0 end 數學,max case course when 語文 then score else 0 end 語文,max case course when 英語 then score else 0 end 英語 fro...

mysql列邊行 mysql 行轉列 列轉行

group concat 函式說明 手冊上說明 該函式返回帶有來自乙個組的連線的非null值的字串結果 通俗點理解,其實是這樣的 group concat 會計算哪些行屬於同一組,將屬於同一組的列顯示出來。要返回哪些列,由函式引數 就是欄位名 決定。分組必須有個標準,就是根據group by指定的列...