当前位置: 代码网 > it编程>数据库>Mysql > MySQL行列转化方式

MySQL行列转化方式

2026年01月23日 Mysql 我要评论
初始化表结构create table `student_scores` ( `student_id` int not null, `student_name` varchar(50) defaul

初始化表结构

create table `student_scores` (
  `student_id` int not null,
  `student_name` varchar(50) default null,
  `math_score` int default null,
  `english_score` int default null,
  `science_score` int default null,
  primary key (`student_id`)
) engine=innodb default charset=utf8mb4 collate=utf8mb4_0900_ai_ci;

insert into student_scores (student_id, student_name, math_score, english_score, science_score) values
(1, 'alice', 85, 90, 78),
(2, 'bob', 76, 88, 92),
(3, 'charlie', 90, 85, 80);

查询表数据:

行转化为列

由于不是我们想要的格式,我们将其转化为列式结构:

-- 行数转化为列
select student_id, student_name, 'math' as subject, math_score as score from student_scores
union all
select student_id, student_name, 'english' as subject, english_score as score from student_scores
union all
select student_id, student_name, 'science' as subject, science_score as score from student_scores;

执行结果: 

列转化为行

 将其作为一张临时表,对其进行行列转化:

select student_id,student_name,
min(case when subject = 'math' then score end ) as math_score,
min(case when subject = 'english' then score end )as english_score,
min(case when subject = 'science' then score end )as science_score 
from  (
    select student_id, student_name, 'math' as subject, math_score as score from student_scores
    union all
    select student_id, student_name, 'english' as subject, english_score as score from student_scores
    union all
    select student_id, student_name, 'science' as subject, science_score as score from student_scores
) as unpivoted
group by unpivoted.student_id,unpivoted.student_name

执行结果:

扩展

union 与 union all区别

  • union:会自动去除合并结果集中的重复记录,只返回唯一的记录。
  • union all:会返回所有记录,包括重复的记录。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com