查找一个字段的值与另一字段中数据的最大值相匹配
我正在尝试编写一个查询来获取与另一个字段(或多个字段)的最大值关联的一个字段的值。假设我有以下数据表:
OrderID CustomerID OrderDate LocationID
1 4 1/1/2001 1001
2 4 1/2/2001 1003
3 4 1/3/2001 1001
4 5 1/4/2001 1001
5 5 1/5/2001 1001
6 5 1/6/2001 1003
7 5 1/7/2001 1002
8 5 1/8/2001 1003
9 5 1/8/2001 1002
按 CustomerID
分组,我想获取最大 OrderDate
,然后获取与以下内容关联的 LocationID
最大OrderDate
。如果有多条记录共享最大订单日期,则从具有最大日期的记录中获取与最大 OrderID
关联的 LocationID
。
最终的数据集应该如下所示:
CustomerID OrderDate LocationID
4 1/3/2001 1001
5 1/8/2001 1002
我一直在尝试编写一个包含大量嵌套子查询和丑陋连接的查询,但我并没有真正取得任何进展。我需要写什么SQL来帮助我得到这个结果。
I'm trying to write a query that gets the value of one field that's associated with the maximum value of another field (or fields). Let's say I have the following table of data:
OrderID CustomerID OrderDate LocationID
1 4 1/1/2001 1001
2 4 1/2/2001 1003
3 4 1/3/2001 1001
4 5 1/4/2001 1001
5 5 1/5/2001 1001
6 5 1/6/2001 1003
7 5 1/7/2001 1002
8 5 1/8/2001 1003
9 5 1/8/2001 1002
Grouping by CustomerID
, I want to get the maximum OrderDate
and then the LocationID
associated with whatever is the maximum OrderDate
. If there are several records that share the maximum order date, then take the LocationID
associated with the maximum OrderID
from among those records with the maximum date.
The final set of data should look like this:
CustomerID OrderDate LocationID
4 1/3/2001 1001
5 1/8/2001 1002
I had been trying to write a query with lots of nested subqueries and ugly joins, but I'm not really getting anywhere. What SQL do I need to write to help me get this result.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您从“客户”表中提取任何列,这可能会优于其他方法。
如果没有,那么仅从订单中提取的
Row_Number
答案可能是最好的。但是,如果您以任何方式受到客户限制,那么CROSS APPLY
将再次是最好的。可能会有很大差距。If you will pull any columns from the Customers table, this will probably outperform other methods.
If not, then the
Row_Number
answer, pulling only from Orders, will probably be best. But if you restrict by Customer in any way, then theCROSS APPLY
will again be best. Possibly by a big margin.技巧是使用子查询作为值,而不是连接:
The trick is to use a subquery as a value, not as a join: