我在查询数据库时尝试生成以下XML。数据库 包含两个表COUNTRY和STATES -
<Country>
<CountryInfo>
<name>USA</name>
<districts>50</districts>
<state>
<stateName>New York</stateName>
<statePop>8,244,910</statePop>
</state>
<state>
<stateName>Chicago</stateName>
<statePop>State Population: 2,707,120</statePop>
</state>
</CountryInfo>
<CountryInfo>
<name>Germany</name>
<districts>16</districts>
<state>
<stateName>Berlin</stateName>
<statePop>3,469,910</statePop>
</state>
<state>
<stateName>Brandenburg</stateName>
<statePop>2,500,000</statePop>
</state>
</CountryInfo>
</Country>
这是一次尝试 -
select ctry.NAME, ctry.DISTRICTS, st.ST_NAME, st.ST_POPULATION
from COUNTRY ctry inner join STATES st on (ctry.NAME=st.COUNTRY);
结果是一个平面文件。
<CountryCollection>
<COUNTRY>
<NAME>USA</NAME>
<DISTRICTS>50</DISTRICTS>
<ST_NAME>New York</ST_NAME>
<ST_POPULATION>8,244,910</ST_POPULATION>
</COUNTRY>
<COUNTRY>
<NAME>USA</NAME>
<DISTRICTS>50</DISTRICTS>
<ST_NAME>CHICAGO</ST_NAME>
<ST_POPULATION> 2,707,120</ST_POPULATION>
</COUNTRY>
<COUNTRY>
<NAME>GERMANY</NAME>
<DISTRICTS>16</DISTRICTS>
<ST_NAME>Berlin</ST_NAME>
<ST_POPULATION>3,469,910</ST_POPULATION>
</COUNTRY>
<COUNTRY>
<NAME>GERMANY</NAME>
<DISTRICTS>50</DISTRICTS>
<ST_NAME>Brandenburg</ST_NAME>
<ST_POPULATION>2,500,000</ST_POPULATION>
</COUNTRY>
</CountryCollection>
我如何对它们进行分组以获得所需的结果?
答案 0 :(得分:1)
由于您正在使用oracle RDBMS,请尝试此操作。
SELECT XMLElement("Country"
, XMLAgg(
XMLElement("CountryInfo"
,XMLFOREST(CTRY.NAME "name", ctry.DISTRICTS "districts")
, xmlAgg(
XMLElement("state",XMLFOREST(st.ST_NAME "stateName", st.ST_POPULATION "statePop")
)
)
)
)
)
FROM COUNTRY ctry
INNER JOIN STATES st
ON (ctry.NAME=st.COUNTRY)
GROUP BY CTRY.NAME ,ctry.DISTRICTS
编辑修改@ A.B.Cade。