0

我在查询数据库时尝试生成以下 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>

我如何将它们分组以获得所需的结果?

4

1 回答 1

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

由@ABCade 编辑以应用更正。

于 2013-06-01T23:39:27.950 回答