当前位置: 首页 > article >正文

MySQL行列转化

初始化表结构:

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区别
  1. UNION:会自动去除合并结果集中的重复记录,只返回唯一的记录。

  2. UNION ALL:会返回所有记录,包括重复的记录。


http://www.kler.cn/a/584947.html

相关文章:

  • 开VR大空间体验馆,如何最低成本获取最大收入?
  • 深度学习环境配置指令大全
  • go-文件缓存与锁
  • C#中除了Dictionary,List,HashSet,HashTable 还有哪些可以保存列表的数据类型?
  • 批量将 Excel 文档中的图片提取到文件夹
  • 如何学习VBA_3.2.20:DTP与Datepicker实现日期的输入
  • 罗德与施瓦茨RTO1044,数字示波器
  • 大数据面试之路 (一) 数据倾斜
  • C++程序设计语言笔记——基本功能:异常处理
  • 如何接入DeepSeek布局企业AI系统开发技术
  • JVM内存结构笔记01-运行时数据区域
  • 记录致远OA服务器硬盘升级过程
  • Qt常用控件之水平布局QHBoxLayout
  • node基础
  • 【YOLOv8】YOLOv8改进系列(6)----替换主干网络之VanillaNet
  • Python 机器学习小项目:手写数字识别(MNIST 数据集)
  • 蓝桥杯备赛-基础练习 day1
  • linux 构建网站环境
  • 【模拟面试】计算机考研复试集训(第二天)
  • Netlify部署vue/react项目,在页面刷新时呈现404解决办法