1. 程式人生 > >資料庫中的行列轉換(橫豎轉換)

資料庫中的行列轉換(橫豎轉換)

豎的資料表橫的資料表)例子:

--建立tb_course表,並插入測試資料

CREATE TABLE tb_course(
NAME VARCHAR(20), ##姓名
course VARCHAR(20), ##課程
grade INT ##成績
);

--測試資料

INSERT INTO tb_course (NAME,course,grade) VALUES('tom','JDBC',20);
INSERT INTO tb_course (NAME,course,grade) VALUES('tom','Hibernate',50);
INSERT INTO tb_course (NAME,course,grade) VALUES('tom','Spring',80);
INSERT INTO tb_course (NAME,course,grade) VALUES('marry','JDBC',30);
INSERT INTO tb_course (NAME,course,grade) VALUES('marry','Hibernate',60);
INSERT INTO tb_course (NAME,course,grade) VALUES('marry','Spring',70);

如圖:


--開始做翻轉

--方法一(在oracle同這種方法):

SELECT NAME,

SUM(DECODE(course,'JDBC',gradem,0)) JDBC,

SUM(DECODE(course,'Hibernate',gradem,0)) Hibernate,

SUM(DECODE(course,'Spring',gradem,0)) Spring

FROM tb_course GROUP BY NAME;

--方法二(在mysql用這種方法):

SELECT NAME,
SUM(IF(course='JDBC',grade,0)) JDBC,
SUM(IF(course='Hibernate',grade,0)) Hibernate,
SUM(IF(course='Spring',grade,0)) Spring
FROM tb_course GROUP BY NAME;

--方法三(這種方法比較麻煩,用自身做一個多表連線,欄位多的時候很容易亂):
SELECT t4.name,t1.JDBC,t2.Hibernate,t3.Spring FROM
(SELECT NAME,grade AS JDBC FROM tb_course WHERE course = 'JDBC') t1,
(SELECT NAME,grade AS Hibernate FROM tb_course WHERE course = 'Hibernate') t2,
(SELECT NAME,grade AS Spring FROM tb_course WHERE course = 'Spring') t3, 
(SELECT DISTINCT NAME FROM tb_course) t4
WHERE t1.name = t4.name AND t2.name = t4.name AND t3.name = t4.name;

執行以上任意一種方法後表會變成:


###########################################################超級分割線###########################################################

(橫的資料表變豎的資料表)例子:

--建立tb_courses表,並插入測試資料

CREATE TABLE tb_courses(
NAME VARCHAR(10),
JDBC INT,
Hibernate INT,
Spring INT
);

--測試資料

INSERT INTO tb_courses VALUES('tom',20,50,80);
INSERT INTO tb_courses VALUES('marry',30,60,70);

如圖:


--開始做翻轉

--方法一(在oracle 與mysql都可用這種方法):

(SELECT NAME,'JDBC' COURSE,JDBC grade FROM tb_courses)
UNION
(SELECT NAME,'Hibernate' COURSE,Hibernate grade FROM tb_courses)
UNION
(SELECT NAME,'Spring' COURSE,Spring grade FROM tb_courses)
ORDER BY NAME DESC;

執行後表會變成:


溫馨提示:

UNION與UNION ALL的區別:union與union all 都是查詢結果的並集,但是union多了一步去重複資料,所以效率上沒union all高,另外union會對查詢結果做排序。