XQuery:如何计算一个值按顺序出现的次数

Sah*_*and 5 xml xquery xpath-2.0

我知道函数 count 可用于计算给定序列中元素的数量,如下所示:

count(result/actors/actor)
Run Code Online (Sandbox Code Playgroud)

在这个 XML 中:

<result>
    <actors>
        <actor id="00000015">Anderson, Jeff</actor>
        <actor id="00000030">Bishop, Kevin</actor>
        <actor id="0000000f">Bonet, Lisa</actor>
        <actor id="916503207">Parillaud, Anne</actor>
        <actor id="916503208">Pitt, Brad</actor>
        <actor id="916503209">Freeman, Morgan</actor>
        <actor id="916503211">Domingo, Placido</actor>
        <actor id="916503210">Sharif, Omar</actor>
        <actor id="1337">Doqumenteriet2011</actor>
    </actors>
</result>
Run Code Online (Sandbox Code Playgroud)

但是如果我想知道一个值在给定序列中出现了多少次呢?

例如,如果我想知道每个演员 (actorRef) 在以下 XML 中出现了多少部电影:

<videos>
    <video id="id1235AA0">
        <title>The Fugitive</title>
        <actorRef>00000003</actorRef>
        <actorRef>00000006</actorRef>
    </video>
    <video id="id1244100">
        <title>Enemy of the State</title>
        <actorRef>00000009</actorRef>
        <actorRef>0000000c</actorRef>
        <actorRef>0000000f</actorRef>
        <actorRef>00000012</actorRef>
    </video>
    <video id="id124E230">
        <title>Clerks</title>
        <actorRef>00000015</actorRef>
        <actorRef>00000018</actorRef>
        <actorRef>0000001b</actorRef>
    </video>
Run Code Online (Sandbox Code Playgroud)

我可以轻松生成所有出现演员的列表,甚至可以让他们在我制作的序列中出现的次数与在 XML 中出现的次数一样多:

result/videos//actorRef
Run Code Online (Sandbox Code Playgroud)

但我不能做任何类似于例如 COUNT() 和 GROUP BY 在 SQL 中一起做的事情,以通过以上 XQuery 行生成的序列中的多重性计数来获取参与者的列表。

我怎样才能产生这个列表?

PS:最终目标是找到出现最多电影的演员。

Tyl*_*gle 3

当您仅存储视频中的演员列表时,这种问题对于文档存储来说并不好。我建议还存储演员所属的视频列表。然后您只需查询拥有最多视频元素的演员即可。

话虽如此,您可以使用现有的数据来完成此操作,但速度不会那么快。您首先需要获取演员的距离列表。然后查询每个演员,过滤包含该演员的视频并进行计数。然后按计数排序。

let $actors := fn:distinct-values($results/videos/video/actorRef)

for $actor in $actors
let $count := fn:count($results/videos/video[actorRef = $actor])
Order by $count
return ($actor, $count)
Run Code Online (Sandbox Code Playgroud)