XQuery入门求助:基于Mondial数据库按大洲分组含岛屿湖泊面积
嘿,你已经开了个好头啦!针对你的数据库作业需求——统计所有含岛屿的湖泊面积并按大洲分组,我帮你补全并优化了XQuery代码,还会一步步拆解逻辑,方便你理解:
完整XQuery代码
let $doc := doc("mondial.xml") let $lakes_with_islands := $doc/mondial/lake[@island] for $lake in $lakes_with_islands let $country_ids := $lake/located_in/@country let $countries := $doc/mondial/country[@id = $country_ids] let $continents := distinct-values($countries/@continent) where exists($continents) group by $continent := $continents return <continent_containing_island_lakes> <name>{$continent}</name> <total_lake_area>{sum($lake/@area)}</total_lake_area> <number_of_lakes>{count($lake)}</number_of_lakes> </continent_containing_island_lakes>
代码逻辑拆解
- 筛选目标湖泊:
$lakes_with_islands精准定位所有带有@island属性的湖泊,和你已经写的初始逻辑完美衔接。 - 关联所属国家:通过湖泊节点下的
located_in子元素的@country属性,匹配到对应的国家节点,这是获取大洲信息的关键桥梁。 - 提取唯一大洲:用
distinct-values处理一个湖泊跨多个国家的情况,确保同一个湖泊不会被重复归类到多个大洲。 - 过滤无效数据:
where exists($continents)会跳过那些没有关联任何大洲的湖泊,避免统计结果出现空值或错误。 - 分组统计输出:按大洲分组后,用
sum()计算总面积、count()统计湖泊数量,最后以结构化的XML返回结果,既符合数据库作业的规范,也方便后续查看。
内容的提问来源于stack exchange,提问作者Augman
相关产品推荐
相关产品推荐

