将行转置为Oracle 10g中的列

时间:2013-11-06 13:08:28

标签: sql oracle oracle10g transpose

我有一个类似于以下内容的表

po_num   | terms type  | terms description
-------------------------------------------
10       | 1           | Desc-10-1
10       | 2           | Desc-10-2
10       | 3           | Desc-10-3
20       | 1           | Desc-20-1
20       | 3           | Desc-20-3
30       |             | 

因此,对于每个采购订单(PO_NUM),可能存在多个协议条款(最多三个 - 1,2,3)或根本没有协议条款。现在,我需要的是将行转换为列 - 也就是说,对于每个po_num,我希望有类似的输出,如下所示。

po_num  | terms1      | termsDesc2  | terms2     | termsDesc2  | terms3    |termsDesc3
---------------------------------------------------------------------------------------
10       | 1           | Desc-10-1  | 2          | Desc-10-2   | 3         |Desc10-3
20       | 1           | Desc-20-1  |            |             | 3         |Desc20-3
30       |             |            |            |             |           |

我没有使用数据透视,因为我没有安装Oracle 11.2。我不想在选择中使用标量子查询,因为使用该方法性能会降低几次。我试图使用以下查询首先连接所有字段,用外部查询拆分它们,但还没有能够做到。

    SELECT po_num,
         RTRIM (
            XMLAGG (
               XMLELEMENT (
                  po_table,
                  po_table.terms_id || '|' || po_table.terms_description || '|')).
            EXTRACT ('//text()'),
            '|')
            po_concat
    FROM po_table
   WHERE 1 = 1
   GROUP BY PO_table.po_num

2 个答案:

答案 0 :(得分:8)

在10g中,您可以使用DECODE功能代替PIVOT

CREATE TABLE po_table (
  po_num NUMBER,
  terms_type NUMBER,
  terms_description VARCHAR2(20)
);

INSERT INTO po_table VALUES(10, 1, 'Desc-10-1');
INSERT INTO po_table VALUES(10, 2, 'Desc-10-2');
INSERT INTO po_table VALUES(10, 3, 'Desc-10-3');
INSERT INTO po_table VALUES(20, 1, 'Desc-20-1');
INSERT INTO po_table VALUES(20, 3, 'Desc-20-3');
INSERT INTO po_table VALUES(30, NULL, NULL);

COMMIT;

SELECT
    po_num,
    MAX(DECODE(terms_type, 1, terms_type)) AS terms1,
    MAX(DECODE(terms_type, 1, terms_description)) AS terms1Desc,
    MAX(DECODE(terms_type, 2, terms_type)) AS terms2,
    MAX(DECODE(terms_type, 2, terms_description)) AS terms2Desc,
    MAX(DECODE(terms_type, 3, terms_type)) AS terms3,
    MAX(DECODE(terms_type, 3, terms_description)) AS terms3Desc
  FROM
    po_table
GROUP BY po_num
ORDER BY po_num;

输出:

    PO_NUM  TERMS1 TERMS1DESC    TERMS2 TERMS2DESC    TERMS3 TERMS3DESC
---------- ------- ------------ ------- ------------ ------- ----------
        10       1 Desc-10-1          2 Desc-10-2          3 Desc-10-3 
        20       1 Desc-20-1                               3 Desc-20-3 
        30                                                             

答案 1 :(得分:2)

这样的事情:

SELECT
po_num,
MAX(CASE WHEN terms_id=1 THEN terms_description ELSE '' END) as termsDesc1, 
MAX(CASE WHEN terms_id=2 THEN terms_description ELSE '' END) as termsDesc2,
MAX(CASE WHEN terms_id=3 THEN terms_description ELSE '' END) as termsDesc3

FROM po_table
GROUP BY po_num