XQuery while using distinct-values()
Asked Answered
A

5

11

XML File

<Cities>
  <Place>
    <City n="New Delhi"></City>
    <City n="Chandigarh"></City>
    <City n="Mumbai"></City>
  </Place>
  <Place>
    <City n="New Delhi"></City>
    <City n="Chandigarh"></City>
  </Place>
  <Place>
    <City n="New Delhi"></City>
    <City n="Mumbai"></City>
  </Place>
</Cities>

I am using following XQuery -

for $x in doc("sample")/Cities/Place/City
   order by $x/@n
   return distinct-values($x/@n)

The result I am expecting is - Chandigarh Mumbai New Delhi

but getting - Chandigarh Chandigarh Mumbai Mumbai New Delhi New Delhi New Delhi

Please tell me where am I going wrong?

Ayer answered 18/6, 2012 at 8:5 Comment(0)
B
14

pls try this -

for $x in distinct-values(doc("sample")/Cities/Place/City/@n)
   order by $x
   return $x

I have checked the same with baseX 7.1 and working smoothly as expected by you :)

Bootee answered 18/6, 2012 at 8:28 Comment(1)
@John-It worked and exactly as I was expecting. Thank you veryAyer
R
6

You are now calling distinct-values on each of the values separately. distinct-values returns the distinct values in a sequence but the sequence now only consists of one element. You should call distinct-values(...) where ... is the sequence of city names.

Rubellite answered 18/6, 2012 at 8:11 Comment(1)
@Simeon-I got it what you want to say. Thank YouAyer
M
0

The distinct-values function

let $items := (1,2,4,4,5,5,9,9,9,9,3,3,2)
let $unique-items-by := distinct-values($items)
return
   <result>   

      <items>
      {
         for $item in $unique-items-by
         return <item>{$item}</item>
      }
      </items>

   </result>
Mcfarlin answered 23/4, 2016 at 4:59 Comment(0)
M
0

The distinct-values function is used
unique-items

 let  $x:=doc("/db/my.xml")
let $unique-items := distinct-values($x)
 for $x in $unique-items

return (
 $unique-items
)
Mcfarlin answered 23/4, 2016 at 5:1 Comment(0)
A
0

If you want to be able to still retain the structure of the data though, chat gpt came up with this solution that is interesting. It uses preceding::user instead of distinct-values

xquery version "1.0-ml";

declare namespace user = "http://example.com/user";

declare variable $users := 
<users>
  <user>
    <id>1</id>
    <email>[email protected]</email>
  </user>
  <user>
    <id>2</id>
    <email>[email protected]</email>
  </user>
  <user>
    <id>3</id>
    <email>[email protected]</email>
  </user>
  <user>
    <id>1</id>
    <email>[email protected]</email>
  </user>
  <user>
    <id>4</id>
    <email>[email protected]</email>
  </user>
</users>;

for $user in $users/user[not(. = preceding::user)]
let $id := $user/id/text()
let $email := $user/email/text()
return 
  <user>
    <id>{$id}</id>
    <email>{$email}</email>
  </user>
Arrowy answered 12/4, 2023 at 19:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.