1

I know there should be a simple solution to this but I can't seem to figure it out. Suppose I have a query which returns something like:

xs:untypedAtomic("A"),
xs:untypedAtomic("B"),
xs:untypedAtomic("C")

and I have another one which returns something like:

xs:untypedAtomic("B"),
xs:untypedAtomic("B"),
xs:untypedAtomic("B"),
xs:untypedAtomic("A"),
xs:untypedAtomic("C"),
xs:untypedAtomic("A")

How do I get the number of occurences for each letter in the second table?

4

2 回答 2

2

使用

for $s in $vMySeq
       return
          ($s, count(index-of($vSeq, $s)))

where$vMySeq是第一个查询$vSeq的结果,是第二个查询的结果。

一个完整的例子

   let $vMySeq := ('A', 'B', 'C'),
       $vSeq := ('B', 'B', 'B', 'A', 'C', 'A')
     return
         for $s in $vMySeq
           return
                  ($s, count(index-of($vSeq, $s)))

结果是

A 2 B 3 C 1
于 2012-12-04T14:02:08.593 回答
2

我提出了两种变体,一种包含 group by 子句,恰好显示了非分组变量 $cntr 的所需特征(参见http://www.w3.org/TR/xquery-30/#id-group-关于如何执行分组的详细信息)

let $seq := ("B", "B","B","A","C","A")
let $cntr := 1
for $it in $seq
group by $it
return <el>{
  attribute num {count($cntr)},
  $it  
}</el>

我的第二个,也许更明显的变体是:

let $seq := ("B", "B","B","A","C","A")
for $v in distinct-values($seq)
    return <el>{
      attribute num {count($seq[. = $v])},
      $v
    }</el>

由于我的回答有点不准确,这里有一个受 Dimitre Novatchev 回答启发的小修正。

而不是使用:

for $v in distinct-values($seq)

你也可以使用

for $v in ("A", "B", "C") (: this is sequence 1 as stated in the question:)

这更类似于问题两个序列,因为这个序列只包含不同的值。

于 2012-12-04T08:59:37.420 回答