SQL列轉行

feri發表於2018-06-05

CREATE TABLE T_score
(
id int primary key auto_increment,
name varchar(20),
subject varchar(30),
score float
)
欄位說明:
id 主鍵
name 名稱
subject 課程
score 分數

新增資料:
INSERT INTO T_score (name,subject,score) values(‘悟空’, ‘語文’, 80);
INSERT INTO T_score (name,subject,score) values( ‘悟空’, ‘數學’, 90);
INSERT INTO T_score (name,subject,score) values( ‘悟空’, ‘英語’, 70);
INSERT INTO T_score (name,subject,score) values( ‘悟空’, ‘生物’, 85);
INSERT INTO T_score (name,subject,score) values( ‘沙僧’, ‘語文’, 80);
INSERT INTO T_score (name,subject,score) values( ‘沙僧’, ‘數學’, 92);
INSERT INTO T_score (name,subject,score) values( ‘沙僧’, ‘英語’, 76);
INSERT INTO T_score (name,subject,score) values( ‘沙僧’, ‘生物’, 88);
INSERT INTO T_score (name,subject,score) values( ‘八戒’, ‘語文’, 60);
INSERT INTO T_score (name,subject,score) values( ‘八戒’, ‘數學’, 82);
INSERT INTO T_score (name,subject,score) values( ‘八戒’, ‘英語’, 96);
INSERT INTO T_score (name,subject,score) values( ‘八戒’, ‘生物’, 78);
INSERT INTO T_score (name,subject,score) values( ‘唐僧’, ‘語文’, 44);
INSERT INTO T_score (name,subject,score) values( ‘唐僧’, ‘數學’, 30);
INSERT INTO T_score (name,subject,score) values( ‘唐僧’, ‘英語’, 55);
INSERT INTO T_score (name,subject,score) values( ‘唐僧’, ‘生物’, 66);

請查詢:
姓名 語文 英語 數學 生物
八戒 60 96 82 78

列轉行:

列轉行

SELECT name,
MAX(CASE subject WHEN ‘語文’ THEN score ELSE 0 END) 語文,
MAX(CASE subject WHEN ‘英語’ THEN score ELSE 0 END) 英語,
MAX(CASE subject WHEN ‘數學’ THEN score ELSE 0 END) 數學,
MAX(CASE subject WHEN ‘生物’ THEN score ELSE 0 END) 生物
FROM t_score GROUP BY name;

使用MAX可以,也可以使用SUM都行。

相關文章