2

我有一张如下所示的表格

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,所以我不能使用 pivot。我不想在选择中使用标量子查询,因为使用这种方法性能会降低数倍。我尝试使用以下查询首先连接所有字段,然后使用外部查询将它们拆分,但还不能这样做。

    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
4

2 回答 2

8

In 10g you can use DECODE function instead of 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;

Output:

    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                                                             
于 2013-11-06T13:23:57.590 回答
2

Something like this:

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
于 2013-11-06T13:24:04.973 回答