xmlagg中的多个xmlagg

时间:2015-09-12 13:28:20

标签: xml oracle plsql aggregate-functions

我遇到问题,我需要创建一个格式如下的xml:

<Root>
<Bank>--Can be repeated
<ID> 
   <Credit>--Can be repeated
             <INFO> --Can be repeated
             </INFO>
   <Credit>
</ID>
</Bank>
</Root>

所以这就像xmlagg,进入xmlagg进入xmlagg

我有一张像这样的表:

BANK|  ID  |  CREDIT |  INFO  ||
1      A1     B1        C1
1      A1     B1        C2
1      A1     B1        C3
1      A1     B2        D1
1      A1     B2        D2
1      A1     B1        C1
2      X1     Y1        Z1

我想要像XML一样使用XML:

<Root>   
<Bank> 1 </Bank>
<ID> A1 </ID>
   <CREDIT> B1 
             <INFO> C1 </INFO>
             <INFO> C2 </INFO>
             <INFO> C2 </INFO>
   </CREDIT>
   <CREDIT> B2 
             <INFO> D1 </INFO>
             <INFO> D2 </INFO>
   </CREDIT>
</ID>
<BANK> 2 </BANK>
<ID> X1 </ID>
<CREDIT> Y1</CREDIT>
<INFO> Z1 </INFO>
</Root>

我希望你明白我的意思,谢谢!

1 个答案:

答案 0 :(得分:0)

您的描述非常模糊,xml定义和示例不一致。还假设xml中的数据应该是不同的。

WITH src (bank, id, credit, info) AS (
    SELECT 1, 'A1', 'B1', 'C1' FROM dual UNION ALL
    SELECT 1, 'A1', 'B1', 'C2' FROM dual UNION ALL
    SELECT 1, 'A1', 'B1', 'C3' FROM dual UNION ALL
    SELECT 1, 'A1', 'B2', 'D1' FROM dual UNION ALL
    SELECT 1, 'A1', 'B2', 'D2' FROM dual UNION ALL
    SELECT 1, 'A1', 'B1', 'C1' FROM dual UNION ALL
    SELECT 2, 'X1', 'Y1', 'Z1' FROM dual
),
credit_data AS (
    SELECT
        bank,
        id,
        XMLELEMENT("Credit", credit,
            XMLAGG(
                XMLELEMENT(INFO, info)
            )
        ) child_nodes
    FROM
        (SELECT DISTINCT * FROM src)
    GROUP BY
        bank, id, credit
),
bank_data AS (
    SELECT
    XMLELEMENT("Bank", bank,
        XMLELEMENT("ID", id,
            XMLAGG(
                child_nodes
            )
        )
    ) bank_nodes
FROM
    credit_data
GROUP BY
    bank, id
)
SELECT
    XMLSERIALIZE(
        DOCUMENT
        XMLELEMENT("Root", NULL,
            XMLAGG(
                bank_nodes
            )
        )
        INDENT SIZE = 2
    ) xml
FROM
    bank_data;