【问题标题】:SQL query to produce XML result生成 XML 结果的 SQL 查询
【发布时间】:2013-06-01 21:13:04
【问题描述】:

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

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

【问题讨论】:

  • 你用的是什么关系型数据库?

标签: sql xml oracle


【解决方案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 的更正。

【讨论】:

  • 它说“表或视图不存在”。 XMLAgg 确实变得像 XMLElement 或 XMLForest 一样粗体。难道XMLAgg不存在?
  • 您的数据库版本是多少?我在 11gR2 上用类似的结构对其进行了测试。
  • @proximityFlying,xmlagg 不是表或视图,而是一个聚合函数,可能表的名称不完全相同?因为查询有效(只需要 group by 子句中的,ctry.DISTRICTS)这里是一个 sqlfiddle 演示 sqlfiddle.com/#!4/26cd6/3
猜你喜欢
  • 1970-01-01
  • 2013-09-10
  • 1970-01-01
  • 1970-01-01
  • 2014-07-10
  • 1970-01-01
  • 2018-09-22
  • 2012-06-20
  • 1970-01-01
相关资源
最近更新 更多