数据如下图,有一个需求,统计scott.emp中不同部门(deptno)的薪资(sal)总数。
如果不考虑行列转换的话,那么最基本的方法是通过deptno进行分组:
SELECT deptno, SUM(sal) FROM scott.emp GROUP BY deptno;
效果如下:
如果要在一行中显示所有部门的薪资总和,那么可以使用SUM(DECODE...)这种方式:
SELECT SUM(DECODE(deptno, 10, sal)) AS dept_10, SUM(DECODE(deptno, 20, sal)) AS dept_20, SUM(DECODE(deptno, 30, sal)) AS dept_30 FROM scott.emp;
效果如下:
或者是使用SUM(CASE...)这种方式做统计:
SELECT SUM(CASE WHEN deptno = 10 THEN sal ELSE 0 END) AS dep_10, SUM(CASE WHEN deptno = 20 THEN sal ELSE 0 END) AS dept_20, SUM(CASE WHEN deptno = 30 THEN sal ELSE 0 END) AS dept_30 FROM scott.emp;
如果使用PIVOT的话,效果和前两种是一样的:
SELECT * FROM (SELECT sal, deptno FROM scott.emp) PIVOT(SUM(sal) sum_sal FOR deptno IN(10 AS dept_10, 20 AS dept_20, 30 AS dept_30));
在PIVOT内可以统计多个,例如,统计各个部门的薪资总和和奖金总和并将结果在一行显示:
SELECT * FROM (SELECT sal, comm, deptno FROM scott.emp) PIVOT(SUM(sal) sum_sal, SUM(NVL(comm, 0)) sum_comm FOR deptno IN(10 AS dept_10, 20 AS dept_20, 30 AS dept_30));
效果如下:
如果数据较多没办法一一列举的话,可以使用PIVOT XML(SUM(..)...IN (ANY))的方式查询,查询出来的结果是一个以CLOB类型存储的XML数据,然后可以在存储过程中处理查询的结果:
SELECT deptno_xml FROM ((SELECT sal, deptno FROM scott.emp) PIVOT XML(SUM(sal) FOR deptno IN (ANY)));
查询出来的结果如下:
<PivotSet> <item><column name="DEPTNO">10</column><column name="SUM(SAL)">8750</column></item> <item><column name="DEPTNO">20</column><column name="SUM(SAL)">10875</column></item> <item><column name="DEPTNO">30</column><column name="SUM(SAL)">9400</column></item></PivotSet>
原文地址:https://www.cnblogs.com/xuanjiaming/p/11691164.html
时间: 2024-11-05 15:44:49