Xquery distinct-values
Asked Answered
C

1

6

I am getting my desired schema. But the one thing i need to do is to eliminate duplicate values. Hence I use distinct values, but what that function does is it displays all the values within one element.

Input Schema:

<?xml version="1.0" encoding="UTF-8"?>
<hotel>
<food>
    <name>Burger</name>
    <cost>20</cost>
</food>
<food>
    <name>Pizza</name>
    <cost>20</cost>
</food>
<food>
    <name>Cola</name>
    <cost>5</cost>
</food>
<food>
    <name>Lemonade</name>
    <cost>5</cost>
</food>
<food>
    <name>Ice Cream</name>
    <cost>10</cost>
</food>
<food>
    <name>Cookies</name>
    <cost>10</cost>
</food>
</hotel>

Output presently:

<type>
<cost>01</cost>
<food>burger fries cola</food>
</type>

Desired:

<type>
<cost>01</cost>
<food>burger</food>
<food>fries</food>
<food>cola</food>
</type>

Basically get all the food for that price.

My Xquery is as follows:

let $cost:= doc("Untitled7.xml")/hotel/food/cost
for $unique in distinct-values(doc("Untitled7.xml")/hotel/food/cost)
let $food:= distinct-values(doc("Untitled7.xml")hotel/food[cost=$unique]/name)
where $unique = $cost
return
<type>
<year>{$unique}</year>
<food>{$food}</food>
</type>

Any help will be appreciated :)

Carrelli answered 2/11, 2013 at 3:9 Comment(0)
S
4

distinct-values() will return a sequence of strings: ('burger', 'fries', 'cola'), but right now you're outputting it at once. What you need to do is iterate over your $food variable in another FLWOR statement:

return
<type>
<year>{$unique}</year>
{
  for $f in $food return <food>{$f}</food>
}
</type>
Sadfaced answered 2/11, 2013 at 13:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.