MySQL行列轉(zhuǎn)化方式
更新時間:2026年01月23日 14:30:42 作者:裊沫
文章介紹了如何將行數(shù)據(jù)轉(zhuǎn)化為列數(shù)據(jù),并展示了如何使用UNION和UNION ALL的區(qū)別,作者分享了個人經(jīng)驗,希望能對大家有所幫助
初始化表結(jié)構(gòu)
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);
查詢表數(shù)據(jù):

行轉(zhuǎn)化為列
由于不是我們想要的格式,我們將其轉(zhuǎn)化為列式結(jié)構(gòu):
-- 行數(shù)轉(zhuǎn)化為列 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;
執(zhí)行結(jié)果:

列轉(zhuǎn)化為行
將其作為一張臨時表,對其進(jìn)行行列轉(zhuǎn)化:
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
執(zhí)行結(jié)果:

擴展
union 與 union all區(qū)別
- UNION:會自動去除合并結(jié)果集中的重復(fù)記錄,只返回唯一的記錄。
- UNION ALL:會返回所有記錄,包括重復(fù)的記錄。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
MySQL安裝后默認(rèn)自帶數(shù)據(jù)庫的作用詳解
這篇文章主要介紹了MySQL安裝后默認(rèn)自帶數(shù)據(jù)庫的作用,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-04-04
mysql中插入隨機字符串?dāng)?shù)據(jù)及常見問題說明
這篇文章主要介紹了mysql中插入隨機字符串?dāng)?shù)據(jù)及常見問題說明,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10

