oracle 行列互转(来自www.askoracle.org整理)
1.使用case when 列转行
SELECT NAME, MAX(CASE WHEN COURSE=‘语文‘ THEN SCORE END) "语文", MAX(CASE WHEN COURSE=‘数学‘ THEN SCORE END) "数学", MAX(CASE WHEN COURSE=‘英语‘ THEN SCORE END) "英语", MAX(CASE WHEN COURSE=‘物理‘ THEN SCORE END) "物理", SUM(SCORE) "总分" FROM stu GROUP BY NAME;
2.一行数据行转列
SELECT NAME, CASE WHEN LV = 1 THEN ‘语文‘ --常量 WHEN LV = 2 THEN ‘数学‘ --常量 WHEN LV = 3 THEN ‘英语‘ --常量 WHEN LV = 4 THEN ‘物理‘ --常量 END 科目, CASE WHEN LV = 1 THEN langu --列名 WHEN LV = 2 THEN math--列名 WHEN LV = 3 THEN english--列名 WHEN LV = 4 THEN pycial--列名 END 成绩 FROM ( SELECT * FROM course, (SELECT LEVEL LV FROM DUAL CONNECT BY LEVEL <= 4) ) --成绩对应的列数 ORDER BY 1, 2;
3.结果集转换成一行
--查询每个部门的人数 SELECT DEPTNO, COUNT(1) CN FROM EMP GROUP BY DEPTNO ORDER BY 1;
--将上面的结果转为一行,可以使用 SUM 或者 COUNT 来求出。 SELECT SUM(CASE WHEN DEPTNO = 10 THEN 1 END) D_10, SUM(CASE WHEN DEPTNO = 20 THEN 1 END) D_20, SUM(CASE WHEN DEPTNO = 30 THEN 1 END) D_30 FROM EMP; --也可以使用下面的方法。 SELECT CASE WHEN DEPTNO = 10 THEN CN END D_10, CASE WHEN DEPTNO = 20 THEN CN END D_20, CASE WHEN DEPTNO = 30 THEN CN END D_30 FROM (SELECT DEPTNO, COUNT(1) CN FROM EMP GROUP BY DEPTNO); --和刚讲的一样,生成了三行三列数据,使用 MAX 来获取。 SELECT MAX(CASE WHEN DEPTNO = 10 THEN CN END) D_10, MAX(CASE WHEN DEPTNO = 20 THEN CN END) D_20, MAX(CASE WHEN DEPTNO = 30 THEN CN END) D_30 FROM (SELECT DEPTNO, COUNT(1) CN FROM EMP GROUP BY DEPTNO);
4.把结果集转换成多行
--每种职位一列,得到下面的结果集 (每种职业的列里面有多余的 NULL,如果使用MAX的话,一列只会取一条最大的值了)
SELECT MAX(CASE JOB WHEN ‘CLERK‘ THEN ENAME END) CLERK, MAX(CASE JOB WHEN ‘ANALYST‘ THEN ENAME END) ANALYST, MAX(CASE JOB WHEN ‘MANAGER‘ THEN ENAME END) MANAGER, MAX(CASE JOB WHEN ‘PRESIDENT‘ THEN ENAME END) PRESIDENT, MAX(CASE JOB WHEN ‘SALESMAN‘ THEN ENAME END) SALESMAN FROM (SELECT ENAME, JOB, --每组都是从 1 开始排序,而每列里面只有一组有数据。也就是 RN 相同的在每列里面只有一条数据 ROW_NUMBER() OVER(PARTITION BY JOB ORDER BY ENAME) RN FROM EMP) GROUP BY RN ORDER BY RN;