我写了一个这样的选择语句:
Select
xmlagg(xmlelement( "Species",
xmlelement("Type",Type),
xmlelement("Name",Name),
xmlforest(case when Tail is not null then Tail else null end "Trait")))
From Table_Animals
Order By Name;
这是我的输入
查询运行良好,但是当我像这样添加 UNION ALL 时:
Select
xmlagg(xmlelement( "Species",
xmlelement("Type",Type),
xmlelement("Name",Name),
xmlforest(case when Tail is not null then Tail else null end "Trait")))
From Table_Animals
UNION ALL
Select
xmlagg(xmlelement( "Species",
xmlelement("Type",Type),
xmlelement("Name",Name),
xmlforest(case when Teeth is not null then Teeth else null end "Trait")))
From Table_Animals
Where Prey is not null
Order By Name;
我收到错误:
ORA-00904: "Name": invalid identifier
在上面的例子中如何正确使用Order By?
我想要的输出是:
<Species>
<Type>Bird<Type>
<Name>Eagle<Name>
<Species>
<Species>
<Type>Mammal<Type>
<Name>Fox<Name>
<Trait>Sharp<Trait>
<Species>
<Species>
<Type>Plant<Type>
<Name>Lettuce<Name>
<Species>
<Species>
<Type>Mammal<Type>
<Name>Rabbit<Name>
<Trait>Short<Trait>
<Species>
<Species>
<Type>Mammal<Type>
<Name>Rabbit<Name>
<Trait>Dull<Trait>
<Species>
<Species>
<Type>Amphibian<Type>
<Name>Snake<Name>
<Trait>Long<Trait>
<Species>
<Species>
<Type>Amphibian<Type>
<Name>Snake<Name>
<Trait>Sharp<Trait>
<Species>
请注意,Snake 和 Rabbit 在输出中出现了两次
您可以使用 XMLAgg 的 order_by_clause
对
XMLAgg的结果进行排序。
在第一步中执行简单的
UNION ALL
(不带 XML)来根据需要复制数据。
最后使用XMLAgg的
order_by_clause
示例数据
create table Table_Animals as
select 'T1' type, 'dog' name, 'tai1' tail, 'Y' prey, 'tee1' teeth from dual union all
select 'T1' type, 'elephant' name, 'tai2' tail, 'Y' prey, 'tee2' teeth from dual union all
select 'T2' type, 'cat' name, 'tai3' tail, null prey, 'tee3' teeth from dual;
查询
with ua as (
select TYPE, NAME, TAIL, PREY, TEETH, Tail as trait from Table_Animals union all
select TYPE, NAME, TAIL, PREY, TEETH, Teeth as trait from Table_Animals where Prey is not null)
Select
xmlagg(xmlelement( "Animal",
xmlelement("Type",Type),
xmlelement("Name",Name),
xmlelement("Trait",Trait)) order by name) xml_col
From ua
;
注意子查询中列
trait
的定义。
记下xml_col
附近的按名称排序
给予
<Animal>
<Type>T2
</Type>
<Name>cat
</Name>
<Trait>tai3
</Trait>
</Animal>
<Animal>
<Type>T1
</Type>
<Name>dog
</Name>
<Trait>tai1
</Trait>
</Animal>
<Animal>
<Type>T1
</Type>
<Name>dog
</Name>
<Trait>tee1
</Trait>
</Animal>
<Animal>
<Type>T1
</Type>
<Name>elephant
</Name>
<Trait>tai2
</Trait>
</Animal>
<Animal>
<Type>T1
</Type>
<Name>elephant
</Name>
<Trait>tee2
</Trait>
</Animal>