Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xquery distinct-values

Tags:

xquery

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 :)

like image 940
user2272525 Avatar asked Nov 02 '13 03:11

user2272525


People also ask

How can I get distinct values in XPath?

We can use distinct-values function which is available in XPath 2.0 for finding the unique values. The fn:distinct-values function returns a sequence of unique atomic values from $arg . Values are compared based on their typed value.

What are distinct values?

Distinct values are all different items in a list, i.e. unique values and 1st occurrences of duplicate values.


1 Answers

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>
like image 183
Ewout Graswinckel Avatar answered Oct 16 '22 10:10

Ewout Graswinckel