【问题标题】:Oracle get distinct in xmlagg functionOracle 在 xmlagg 函数中变得与众不同
【发布时间】:2020-11-23 23:53:27
【问题描述】:

我需要在 xmlagg 函数中变得与众不同。例如下一个查询

select
       xmlagg(xmlelement(e, names.name || ' ')).extract('//text()').getclobval()
           within group (order by names.name ) names,
       xmlagg(xmlelement(e, actions.action || ' ')).extract('//text()').getclobval()
           within group ( order by actions.action) actions
from
json_table('[{"name": "Name1"}, {"name": "Name2"}, {"name": "Name3"}]', '$[*]'
                    columns (name varchar2 path '$.name')) names,
json_table('[{"action": "Call"}, {"action": "Write"}, {"action": "Write"}]', '$[*]'
                    columns (action varchar2 path '$.action')) actions

返回

NAMES                                                 | ACTIONS
-----------------------------------------------------------------------------------------------------------
Name1 Name1 Name1 Name2 Name2 Name2 Name3 Name3 Name3 | Call Write Write Call Write Write Call Write Write 

我需要得到类似的结果

NAMES             | ACTIONS
-------------------------------
Name1 Name2 Name3 | Call Write  

【问题讨论】:

    标签: sql json xml oracle subquery


    【解决方案1】:

    我认为首先在子查询中选择不同的值更简单:

    select 
        (
            select xmlagg(xmlelement(e, name || ' ') order by name).extract('//text()').getclobval()
            from (
                select distinct name
                from json_table(
                    '[{"name": "Name1"}, {"name": "Name2"}, {"name": "Name3"}]', '$[*]'
                    columns (name varchar2 path '$.name')
                ) names
            ) n
        ) names,
        (
            select xmlagg(xmlelement(e, action || ' ') order by action).extract('//text()').getclobval()
            from (
                select distinct action
                from json_table(
                    '[{"action": "Call"}, {"action": "Write"}, {"action": "Write"}]', '$[*]'
                    columns (action varchar2 path '$.action')
                ) actions
            ) a
        ) actions
    from dual
    

    注意xmlagg()order by 更适合函数中。

    Demo on DB Fiddle

    姓名 |行动 :----------------- | :---------- 姓名1 姓名2 姓名3 |调用写入

    【讨论】:

    • 1.在组内不分组 xmlagg 值。它引发异常 ORA-00923: FROM keyword not found where expected
    • @KamoPetrosyan:我修复了查询,并在我的答案中添加了一个 db fiddle。
    猜你喜欢
    • 1970-01-01
    • 2022-10-25
    • 2015-11-20
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    • 2015-09-08
    • 2019-09-16
    • 1970-01-01
    相关资源
    最近更新 更多