简体   繁体   中英

XQuery join result

I have a XML that looks like this:

<?xml version="1.0"?>
<root>
  <flight>
    <number>10001</number>
    <airport>LAX</airport>
    <dest>
      <airport>SFO</airport>
    </dest>
  </flight>
  <flight>
    <number>10002</number>
    <airport>LAX</airport>
    <dest>
      <airport>JFK</airport>
    </dest>
  </flight>
  <flight>
    <number>10003</number>
    <airport>JFK</airport>
    <dest>
      <airport>LAX</airport>
    </dest>
  </flight>
</root>

Using XQuery I need to get something like this:

<res>
    <airport code="LAX">
        <deps>2</deps>
        <dests>1</deps>
    </airport>
    <airport code="JFK">
        <deps>1</deps>
        <dests>1</deps>
    </airport>
    <airport code="SFO">
        <deps>0</deps>
        <dests>1</deps>
    </airport>
</res>

I did it, and can get the correct result, however, my query can only find deps or dests , but not both.

Here is how I approached the problem.

let $all := doc("flights.xml")/root
for $airports in distinct-values($all/flight//*/airport) (:here I get all airport codes:)
order by $airports 

for $nr-dep in $all/flight/airport

where $nr-dep = $airports 
group by $airports 

return <res>
          <airport name="{$airports}"><deps>{count($nr-dep)}</deps></airport>
       </res>

Here I get the departure count. I can easily get destionations by replacing for $nr-dep in $all/flight/airport with for $nr-dep in $all/flight/dest/airport however I cannot find a way to show both at the same result like the expected XML.

Here is a version using group by :

<res>{
    for $airport in //airport
    group by $code := $airport/text()
    order by $code
    return <airport code="{$code}">
        <deps>{ count($airport/parent::flight) }</deps>
        <dests>{ count($airport/parent::dest) }</dests>
    </airport>
}</res>

Why not simply:

for $airport in distinct-values($all//airport)
order by $airport
return <airport code="{$airport}">
  <deps>{count($all//flight/airport[. = $airport])}</deps>
  <dests>{count($all//dest/airport[. = $airport])}</dests>
</airport>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM