将行转置为Oracle 10g中的列

Ahm*_*dov 2 sql oracle transpose oracle10g

我有一张表如下所示

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       |             | 
Run Code Online (Sandbox Code Playgroud)

因此,对于每个采购订单(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       |             |            |            |             |           |
Run Code Online (Sandbox Code Playgroud)

我没有使用数据透视,因为我没有安装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
Run Code Online (Sandbox Code Playgroud)

Prz*_*lej 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;
Run Code Online (Sandbox Code Playgroud)

输出:

    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