如何在 XQuery 中获取计算值的最大值?
How to get the maximum of a calculated value in XQuery?
我有很多订单如下:
<order id="1">
<TargetPrice>100</TargetPrice>
<Qty>2</Qty>
</order>
我需要一个 Xquery 来获取最高价值的订单(其中价值是 TargetPrice*Qty)
我该怎么做?
按值降序排序,return 第一个元素。
(
for $order in //order
let $value := $order/TargetPrice * $order/Qty
order by $value descending
return $order
)[1]
您可能想要实现函数和运算符 3.1 规范的 D.6.1 中的函数。这比 "sort and take the first" 解决方案有点冗长,但它可能更快(原则上它是可流式传输的),并且代码可高度重用。
D.6.1 eg:highest
函数 eg:highest returns 对提供的函数具有最高值的项目。
XSLT 实现
(剪断)
XQuery 实现
declare function eg:highest(
$seq as item()*
$f as function(item()) as xs:anyAtomicType)
as item()* {
fn:fold-left(
fn:tail($seq), fn:head($seq),
function($highestSoFar as item()*, $this as item()*) as item()* {
let $thisValue := $f($this)
let $highestValue := $f($highestSoFar[1])
return
if ($thisValue gt $highestValue)
then $this
else if ($thisValue eq $highestValue)
then ($highestSoFar, $this)
else $highestSoFar
})
};
要找到薪水最高的员工,函数可以这样调用:
eg:highest(//employee, function($emp){$emp/salary})
另一种选择是使用 simple map operator !
and calculate the product of TargetPrice * Qty
for the sequence of items, and then select the max()
值,并在谓词中使用:
let $maxVal := max(//order ! (TargetPrice * Qty))
return //order[(TargetPrice * Qty) eq $maxVal]
我有很多订单如下:
<order id="1">
<TargetPrice>100</TargetPrice>
<Qty>2</Qty>
</order>
我需要一个 Xquery 来获取最高价值的订单(其中价值是 TargetPrice*Qty)
我该怎么做?
按值降序排序,return 第一个元素。
(
for $order in //order
let $value := $order/TargetPrice * $order/Qty
order by $value descending
return $order
)[1]
您可能想要实现函数和运算符 3.1 规范的 D.6.1 中的函数。这比 "sort and take the first" 解决方案有点冗长,但它可能更快(原则上它是可流式传输的),并且代码可高度重用。
D.6.1 eg:highest
函数 eg:highest returns 对提供的函数具有最高值的项目。
XSLT 实现
(剪断)
XQuery 实现
declare function eg:highest(
$seq as item()*
$f as function(item()) as xs:anyAtomicType)
as item()* {
fn:fold-left(
fn:tail($seq), fn:head($seq),
function($highestSoFar as item()*, $this as item()*) as item()* {
let $thisValue := $f($this)
let $highestValue := $f($highestSoFar[1])
return
if ($thisValue gt $highestValue)
then $this
else if ($thisValue eq $highestValue)
then ($highestSoFar, $this)
else $highestSoFar
})
};
要找到薪水最高的员工,函数可以这样调用:
eg:highest(//employee, function($emp){$emp/salary})
另一种选择是使用 simple map operator !
and calculate the product of TargetPrice * Qty
for the sequence of items, and then select the max()
值,并在谓词中使用:
let $maxVal := max(//order ! (TargetPrice * Qty))
return //order[(TargetPrice * Qty) eq $maxVal]