【问题标题】:XQuery: Returning the highest value after orderingXQuery:排序后返回最大值
【发布时间】:2020-04-12 19:08:18
【问题描述】:

我还是 XQuery 的新手,但我几乎已经弄清楚了这个查询,但它只需要返回具有最多作者的元素的 proteinID 和 numberOfAuthors,但是它目前返回所有这些而不是只返回作者数量最多的元素。

我的查询是

for $i in doc("test.xml")/ProteinDatabase/ProteinEntry
let $author-count := count($i/reference/refinfo/authors)
let $proteinID := $i/@id
where $author-count = max($author-count)
order by $author-count descending
return ((<proteinID>{data($proteinID)}</proteinID>,
<numberOfAuthors>{data($author-count)}</numberOfAuthors>))

返回:

<proteinID>QRHUA4</proteinID>
<numberOfAuthors>47</numberOfAuthors>
<proteinID>PLHU</proteinID>
<numberOfAuthors>29</numberOfAuthors>
<proteinID>LPHUB</proteinID>
<numberOfAuthors>29</numberOfAuthors>

等等。

我只想返回第一个 proteinID,最高的是 47,如下所示:

<proteinID>QRHUA4</proteinID>
<numberOfAuthors>47</numberOfAuthors>

我已经尝试了一些东西,比如我在其中的 where 语句

where $author-count = max($author-count)

但它似乎并没有真正做任何事情。我也尝试了一些定位的东西,只选择了第一个索引,但它似乎只返回 ID QRHUA4,而不是 numberOfAuthors

【问题讨论】:

  • 请发布一些示例 xml
  • 当然很抱歉,它只是很长,所以我省略了它
  • 最少的样本就可以了
  • 用一个例子更新了 OP

标签: xml xpath xquery


【解决方案1】:

好吧,您可以简单地选择结果序列中的第一项

(for $i in doc("proteindb.xml")/ProteinDatabase/ProteinEntry
let $author-count := count($i/reference/refinfo/authors)
let $proteinID := $i/@id
where $author-count = max($author-count)
order by $author-count descending
return ((<proteinID>{data($proteinID)}</proteinID>,
<numberOfAuthors>{data($author-count)}</numberOfAuthors>)))[1]

head(for $i in doc("proteindb.xml")/ProteinDatabase/ProteinEntry
let $author-count := count($i/reference/refinfo/authors)
let $proteinID := $i/@id
where $author-count = max($author-count)
order by $author-count descending
return ((<proteinID>{data($proteinID)}</proteinID>,
<numberOfAuthors>{data($author-count)}</numberOfAuthors>)))

【讨论】:

  • 感谢您的帮助!
  • 对于您的第一个解决方案,是否可以选择两个位置?因为 [1] 将返回 proteinID,而不是相关的 numberOfAuthors,因为它位于位置 [2]。如果可能,我需要返回位置 [1] 和 [2]
  • @BenWhitely,抱歉,我没有注意到您返回了一个序列,其中您需要两个项目,但是例如 subsequence(for... return ..., 1, 2) 或者当然是 (...)[position() = (1, 2)]
  • 是的,我试着只做 [1,2](就像你的第一个查询,用 [1,2] 替换 [1])来获取第一个和第二个值,因为这对我来说很有意义,但我只是得到一个“没有为(1,2)定义的有效布尔值”错误。这些是我的第一个 XQuery 查询,所以我显然遗漏了一些明显的东西
  • 我之前的评论有两个建议,试试吧。
【解决方案2】:
for $i in //ProteinEntry[reference/refinfo/authors/count(*) = 
                         max(//ProteinEntry/reference/refinfo/authors/count(*))
                        ]
let $author-count := count($i/reference/refinfo/authors/author)
let $proteinID := $i/@id
return ((<proteinID>{$proteinID}</proteinID>,
<numberOfAuthors>{$author-count}</numberOfAuthors>))

小提琴:https://xqueryfiddle.liberty-development.net/jyH9Xv4/1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-16
    • 2017-09-25
    • 1970-01-01
    相关资源
    最近更新 更多