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

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.dtcms.com/a/67704.html

相关文章:

  • Vision Mamba论文精读笔记
  • 基于Redis实现限流的几种方式
  • MySQL 连接的使用
  • 嵌入式Zephyr RTOS面试题及参考答案
  • 【原创】springboot+vue校园外卖订餐网系统设计与实现
  • Kubeflow 2025 全栈式机器学习平台部署指南(云原生+量子混合计算)
  • 【Python办公自动化】—Excel中相同编号自动添加-1-2-3...
  • Linux--git
  • python学习笔记-mysql数据库操作
  • C语言刷题第三章(上)
  • Windows 系统下安装 RabbitMQ 的详细指南
  • word甲烷一键下标——宏
  • Echarts 柱状或折线或其他多数据图表自动向右滚动
  • centos没有ll
  • 【vue+excel】导出excel(目前是可以导出两个sheet)
  • dify+mysql的诗词助手
  • Appium高级操作--从源码角度解析--模拟复杂手势操作
  • cursor使用
  • 【LeetCode110】平衡二叉树
  • AutoGen学习笔记系列(十七)Examples - Literature Review
  • 基于deepseek的图像生成系统
  • 【OpenFeign 面试专题】
  • Mysql小知识
  • 晶晨S905M/晶晨S905L2芯片-原机安卓4升级安卓7.1.2-通刷线刷固件包
  • 《九章云络书·织网布阵玄机》上篇
  • Spring Boot项目中集成sa-token实现认证授权和OAuth 2.0第三方登录
  • 解决Windows版Redis无法远程连接的问题
  • Linux Nginx安装部署、注册服务
  • (全)2024下半年真题 系统架构设计师 综合知识 答案解析02
  • MTK Android12 最近历史任务 最左侧的清除历史任务改到页面底部