从分组结果中获取最大值的行

发布于 2024-12-07 09:16:52 字数 323 浏览 1 评论 0原文

我有如下 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

貪欢 2024-12-14 09:16:52

您需要嵌套查询,但如果使用 分析函数

select customerID, sumOrderCost from
(
    select customerID, sumOrderCost,
        rank() over (order by sumOrderCost desc) as rn
    from (
        select c.customerID, sum(o.orderCost) as sumOrderCost
        from customer c, orders o
        where c.customerID=o.customerID
        group by c.customerID
    )
)
where rn = 1;

rank() 函数根据 sum() 值对原始查询的结果进行排名,然后您只选择排名最高的那些 - 即行)总订单成本最高。

如果多个客户的订单总成本相同,则两者都会返回。如果这不是您想要的,您将必须决定如何确定要使用哪个单个结果。例如,如果您想要最低的客户 ID,请将其添加到排名函数中:

select customerID, sumOrderCost,
    rank() over (order by sumOrderCost desc, customerID) as rn

您可以调整原始查询以返回其他数据,仅用于排序,而不是将其包含在外部 select 中。

You need a nested query, but you don't have to access the tables twice if you use analytic functions.

select customerID, sumOrderCost from
(
    select customerID, sumOrderCost,
        rank() over (order by sumOrderCost desc) as rn
    from (
        select c.customerID, sum(o.orderCost) as sumOrderCost
        from customer c, orders o
        where c.customerID=o.customerID
        group by c.customerID
    )
)
where rn = 1;

The rank() function ranks the results from your original query by the sum() 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:

select customerID, sumOrderCost,
    rank() over (order by sumOrderCost desc, customerID) as rn

You can adjust you original query to return other data instead, just for the ordering, and not include it in the outer select.

桃扇骨 2024-12-14 09:16:52

您需要为此创建嵌套查询。
两个查询。

You need to create nested query for this.
Two queries.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文