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) には、複数の契約条件 (最大 3 - 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でスカラーサブクエリを使用したくありません。次のクエリを使用して、最初にすべてのフィールドを連結し、それらを外側のクエリで分割しようとしましたが、まだ実行できていません。

    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

DECODE10gでは、代わりに関数を使用できます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 説明-10-1 2 説明-10-2 3 説明-10-3
        20 1 説明-20-1 3 説明-20-3
        30                                                             
于 2013-11-06T13:23:57.590 に答える
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
于 2013-11-06T13:24:04.973 に答える