MySQL行列互轉

列轉行:

構建用於行轉列的成績表:

# 創建學生成績表scores1,用於行轉列測試
create table scores1(
sname varchar(10) not null default '',
course varchar(10) not null default '',
score int not null default 0
)engine myisam charset utf8mb4;

# 向成績表scores1中插入數據
insert into scores1 values
('張三','語文',74),
('張三','數學',83),
('張三','物理',93),
('李四','語文',74),
('李四','數學',84),
('李四','物理',94);

查看成績表scores1的表結構:

select * from scores1

使用case when函數實現行轉列:

select sname,
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 scores1
group by sname

使用if函數實現行轉列:

select sname,
max(if(course='語文',score,0)) as 語文,
max(if(course='數學',score,0)) as 數學,
max(if(course='物理',score,0)) as 物理
from scores1
group by sname

行轉列:

構建用於列轉行的成績表:

# 創建學生成績表scores2,用於列轉行測試
create table scores2(
sname varchar(10) not null default '',
語文 int not null default 0,
數學 int not null default 0,
物理 int not null default 0
)engine myisam charset utf8mb4;

# 向成績表scores2中插入數據
insert into scores2 values
('張三',74,83,93),
('李四',74,84,94);

查看成績表scores2的表結構:

select * from scores2

使用union實現列轉行:

select sname,'語文' as course, 語文 as score from scores2
union select sname, '數學' as course, 數學 as score from scores2
union select sname, '物理' as course, 物理 as score from scores2
order by sname

# 上述代碼中'語文','數學'和'物理'是新建立的course字段中的值
# 而語文、數學和物理均指成績表scores2中的字段

 

參考:

https://blog.csdn.net/qq_41080850/article/details/95357987

https://www.cnblogs.com/ken-jl/p/8570518.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章