gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 02:03:38 24 4
gpt4 key购买 nike

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

count(result/actors/actor)

在这个 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>

但是,如果我想知道某个值在给定序列中出现了多少次怎么办?

例如,如果我想知道每个 Actor (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>

我可以很容易地生成所有出现的 Actor 的列表,甚至可以让他们在我生成的序列中出现的次数与在 XML 中出现的次数一样多:

result/videos//actorRef

但我无法做任何类似的事情,例如 COUNT() 和 GROUP BY 在 SQL 中一起做的事情,通过上面的 XQuery 行生成的序列中的多重性计数来获取 Actor 列表。

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

PS:最终目标是找到出演电影次数最多的 Actor 。

最佳答案

这是一个纯 XPath 2.0 表达式(XPath 2.0 是 XQuery 的一个真子集),它生成 actorRef 值的序列,标识参与的参与者在最大数量的电影中:

 for $maxMovies in 
max(for $actorId in distinct-values(/*/*/actorRef)
return
count(index-of(/*/*/actorRef, $actorId))
)
return
(/*/*/actorRef)[index-of(/*/*/actorRef, .)[$maxMovies]]/string()

在以下源 XML 文档上计算此表达式时:

<videos>
<video id="id1235AA0">
<title>The Fugitive</title>
<actorRef>00000003</actorRef>
<actorRef>00000009</actorRef>
<actorRef>0000000x</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>
</videos>

产生了正确的、想要的结果:

00000009

使用 XPath 3.0(XQuery 3.0 的适当子集)甚至可以写得更短:

let $vSeq := /*/*/actorRef/string()
return
for $maxMovies in
max(for $actorId in distinct-values($vSeq)
return
index-of($vSeq, $actorId) ! last()
)
return
$vSeq[index-of($vSeq, .)[$maxMovies]]

这可以使用简单的映射运算符 (!) 进一步缩短,以避免任何 for-expression:

let $vSeq := /*/*/actorRef/string(),
$maxOccurs :=
max(distinct-values($vSeq) ! count(index-of($vSeq, .)) )
return
$vSeq[index-of($vSeq, .)[$maxOccurs]]

关于xml - XQuery:如何计算一个值按顺序出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32925486/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com