XQuery - group by and count
Asked Answered
E

1

8

This is the structure of my XML file -

<A>
  <Name t="Mr.">James Bond</Name>
  <Name t="Mr.">Allen Bond</Name>
  <Name t="Mr." p="X">James Bond</Name>
  <Name t="Mr." p="X">James Bond</Name>
  <Name t="Mr.">James Bond</Name>
  <Name t="Mrs.">James Bond</Name>
  <Name t="Mrs.">James Bond</Name>
  <Name t="Mr.">James Bond</Name>
  <Name t="Mrs." p="Y">James Bond</Name>
  <Name t="Mrs." p="Y">James Bond</Name>
</A>

The output I am expecting is -

<A>
  <N>Allen Bond Mr - 1</N>
  <N>James Bond Mr - 3</N>
  <N>James Bond Mr, X - 2</N>
  <N>James Bond Mrs - 2</N>  
  <N>James Bond Mrs, Y - 2</N>
</A>

I am able to get the distinct names but cant add the count...

Encasement answered 25/12, 2012 at 11:34 Comment(1)
possible duplicate of Counting values obtained using the substring function in XQueryBioastronautics
E
10

XQuery 3.0 solution with group by:

<A>{
  for $name in //Name
  let $full :=
    if(not($name/@p)) then concat($name, ' ', $name/@t)
    else concat($name, ' ', $name/@t, ', ', $name/@p)
  group by $full
  return <N>{$full, '-', count($name)}</N>
}</A>

XQuery 1.0 solution with distinct-values($arg):

<A>{
  let $names :=
    for $name in //Name
    return if(not($name/@p)) then concat($name, ' ', $name/@t)
    else concat($name, ' ', $name/@t, ', ', $name/@p)
  for $name in distinct-values($names)
  return <N>{$name, '-', count($names[. eq $name])}</N>
}</A>
Empire answered 25/12, 2012 at 12:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.