从分组结果中获取最大值的行
我有如下 sql:
select
c.customerID, sum(o.orderCost)
from customer c, order o
where c.customerID=o.customerID
group by c.customerID;
这将返回一个列表,
customerID, orderCost
其中 orderCost
是客户所下的所有订单的总成本。我想选择支付给我们最多的客户(订单成本最高的客户)。我需要为此创建一个嵌套查询吗?
I have sql such as:
select
c.customerID, sum(o.orderCost)
from customer c, order o
where c.customerID=o.customerID
group by c.customerID;
This returns a list of
customerID, orderCost
where orderCost
is the total cost of all orders the customer has made. I want to select the customer who has paid us the most (who has the highest orderCost). Do I need to create a nested query for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要嵌套查询,但如果使用 分析函数。
rank()
函数根据sum()
值对原始查询的结果进行排名,然后您只选择排名最高的那些 - 即行)总订单成本最高。如果多个客户的订单总成本相同,则两者都会返回。如果这不是您想要的,您将必须决定如何确定要使用哪个单个结果。例如,如果您想要最低的客户 ID,请将其添加到排名函数中:
您可以调整原始查询以返回其他数据,仅用于排序,而不是将其包含在外部
select
中。You need a nested query, but you don't have to access the tables twice if you use analytic functions.
The
rank()
function ranks the results from your original query by thesum()
value, then you only pick those with the highest rank - that is, the row(s) with the highest total order cost.If more than one customer has the same total order cost, this will return both. If that isn't what you want you'll have to decide how to determine which single result to use. If you want the lowest customer ID, for example, add that to the ranking function:
You can adjust you original query to return other data instead, just for the ordering, and not include it in the outer
select
.您需要为此创建嵌套查询。
两个查询。
You need to create nested query for this.
Two queries.