XQuery - 分组和计数

时间:2012-12-25 11:34:37

标签: xml xquery

这是我的XML文件的结构 -

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

我期待的输出是 -

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

我能够获得不同的名字,但无法添加计数......

1 个答案:

答案 0 :(得分:6)

group by的XQuery 3.0解决方案:

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

distinct-values($arg)的XQuery 1.0解决方案:

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