SQL查询和优化(八)

列转行

测试数据如下:
DROP TABLE TEST PURGE;
CREATE TABLE test AS
SELECT * 
    FROM (SELECT deptno,sal FROM emp)
    POVIT ( COUNT(*) AS ct,SUM(sal) AS s
        FOR deptno 
        IN(10 AS deptno_10, 20 AS deptno_20, 30 AS deptno_30)
    )
要求把三个部门的“人次”转为一列显示。以前可用UNION ALL 来写
SELECT '10' AS 部门编码,DEPTNO_10_CT AS 人次 FROM test 
UNION ALL
SELECT '20' AS 部门编码,DEPTNO_10_CT AS 人次 FROM test 
UNION ALL
SELECT '30' AS 部门编码,DEPTNO_10_CT AS 人次 FROM test 
用UNPIVOT就比较简单,语法如下:
SELECT ....  
FROM <table-expr>  
   UNPIVOT [include nulls|exclude nulls]  
     (  
      (<column>)  
      FOR <pivot-column> IN (<value1>, <value2>,..., <valuen>)  
        ) AS <alias>  
WHERE .....  

实例:

SELECT *
    FROM test 
        UPIVOT(人次 FOR deptno IN(deptno_10_CT,deptno_20_CT,deptno_30_CT));

将结果集反向转置为一列

SELECT  emps
    FROM (SELECT ename,job,to_char(sal) AS sal, null AS T_COL)
    UNPOVIT INCLUDE NULLS (emps FOR COL IN (ename,job,sal,T_COL));

EMPS
________
CLARK
MANAGER
2450

KING
PRESIDENT
5000

MILLER 
CLERK
1300 

已选择12行

选自《Oracle 查询优化改写技巧与案例》 有教无类 落落 著

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值