Oracle 行转列(pivot、wm_concat、decode)使用总结

CREATE TABLE CC
(Student NVARCHAR2(2),Course NVARCHAR2(2),Score INT
);

INSERT into CC
select N‘张三‘,N‘语文‘,78 from dual union all
select N‘张三‘,N‘数学‘,87 from dual union all
select N‘张三‘,N‘英语‘,82 from dual union all
select N‘张三‘,N‘物理‘,90 from dual union all
select N‘李四‘,N‘语文‘,65 from dual union all
select N‘李四‘,N‘数学‘,77 from dual union all
select N‘李四‘,N‘英语‘,65 from dual union all
select N‘李四‘,N‘物理‘,85 from dual ;
commit;

/*
--希望看到查询結果:
李四 77 85 65 65 292
张三 87 90 82 78 337
*/
---1 decode 方法
SELECT
student,
MAX(DECODE(COURSE, ‘语文‘, SCORE)) A,
MAX(DECODE(COURSE, ‘数学‘, SCORE)) B,
MAX(DECODE(COURSE, ‘英语‘, SCORE)) C,
MAX(DECODE(COURSE, ‘物理‘, SCORE)) D,
SUM(SCORE) TOTAL
FROM
CC
GROUP BY
student;

--2 使用wm_concat方法
SELECT STUDENT,WM_CONCAT(SCORE),SUM(SCORE) FROM CC GROUP BY STUDENT;
--3 使用Oracle 11g pivot方法
SELECT KIN.*, KIN.a + KIN.b + KIN.c + KIN.d AS TOTAL
FROM (SELECT *
FROM CC PIVOT(MAX(SCORE) FOR COURSE IN(‘语文‘ AS A,
‘数学‘ AS B,
‘英语‘ AS C,
‘物理‘ AS D))) KIN;

 

 

转自:http://blog.csdn.net/jxzkin/article/details/7949629

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。