我正在尝试使用 Altova XMLSpy 和 XQuery 1.0 返回每个客户的最新订单。
在 SQL 中,查询是这样的:
SELECT `Order ID`, `Customer ID`, `Employee ID`, `Order Date`
FROM Orders AS O1
WHERE `Order Date` =
(SELECT MAX(`Order Date`)
FROM Orders AS O2
WHERE O2.[Customer ID] = O1.[Customer ID]);
它返回 16 行,但我无法获得与在 XQuery 中工作类似的任何内容。
我尝试了多种代码变体,我认为最接近的是:
<result>
{
for $cust in distinct-values(doc("Orders.xml")//Orders/Customer_x0020_ID)
return
<Customer>
{
for $order in doc("Orders.xml")//Orders
where $cust = $order/Customer_x0020_ID
return max(xs:string($order/Order_x0020_Date))
}
</Customer>
}
</result>
为 XML 已从 MS Access 导出的可怕标签名称道歉。
请帮忙!提前致谢。
<Orders>
<Order_x0020_ID>30</Order_x0020_ID>
<Employee_x0020_ID>9</Employee_x0020_ID>
<Customer_x0020_ID>27</Customer_x0020_ID>
<Order_x0020_Date>2006-01-15T00:00:00</Order_x0020_Date>
</Orders>
编辑: 在尝试了 joemfb 的解决方案后,当我只需要最近的(或最大日期)时,我会收到每个客户的所有订单:
<Customer>
<Order_x0020_ID>57</Order_x0020_ID>
<Customer_x0020_ID>27</Customer_x0020_ID>
<Employee_x0020_ID>9</Employee_x0020_ID>
<Order_x0020_Date>2006-04-22T00:00:00</Order_x0020_Date>
<Order_x0020_ID>30</Order_x0020_ID>
<Customer_x0020_ID>27</Customer_x0020_ID>
<Employee_x0020_ID>9</Employee_x0020_ID>
<Order_x0020_Date>2006-01-15T00:00:00</Order_x0020_Date>
</Customer>
<Customer>
<Order_x0020_ID>80</Order_x0020_ID>
<Customer_x0020_ID>4</Customer_x0020_ID>
<Employee_x0020_ID>2</Employee_x0020_ID>
<Order_x0020_Date>2006-04-25T17:03:55</Order_x0020_Date>
<Order_x0020_ID>58</Order_x0020_ID>
<Customer_x0020_ID>4</Customer_x0020_ID>
<Employee_x0020_ID>3</Employee_x0020_ID>
<Order_x0020_Date>2006-04-22T00:00:00</Order_x0020_Date>
<Order_x0020_ID>61</Order_x0020_ID>
<Customer_x0020_ID>4</Customer_x0020_ID>
<Employee_x0020_ID>9</Employee_x0020_ID>
<Order_x0020_Date>2006-04-07T00:00:00</Order_x0020_Date>
<Order_x0020_ID>34</Order_x0020_ID>
<Customer_x0020_ID>4</Customer_x0020_ID>
<Employee_x0020_ID>9</Employee_x0020_ID>
<Order_x0020_Date>2006-02-06T00:00:00</Order_x0020_Date>
<Order_x0020_ID>31</Order_x0020_ID>
<Customer_x0020_ID>4</Customer_x0020_ID>
<Employee_x0020_ID>3</Employee_x0020_ID>
<Order_x0020_Date>2006-01-20T00:00:00</Order_x0020_Date>
</Customer>