数据库中的行列转换(横竖转换)

竖的数据表横的数据表)例子:

--创建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);

如图:

数据库中的行列转换(横竖转换)_第1张图片

--开始做翻转

--方法一(在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;

执行后表会变成:

数据库中的行列转换(横竖转换)_第2张图片

温馨提示:

UNION与UNION ALL的区别:union与union all 都是查询结果的并集,但是union多了一步去重复数据,所以效率上没union all高,另外union会对查询结果做排序。








你可能感兴趣的:(数据库)