首页 > 代码库 > Oracle 行转列(pivot、wm_concat、decode)使用总结
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
Oracle 行转列(pivot、wm_concat、decode)使用总结