选择所有订单中价格最高的客户

时间:2019-06-21 08:38:57

标签: sql oracle select greatest-n-per-group

enter image description here我想列出客户ID最高的订单价格。请查看下图的订单。

2 个答案:

答案 0 :(得分:0)

SQL DEMO

 SELECT *
 FROM (
         SELECT "customerid", SUM("price")
         FROM  Orders
         GROUP BY "customerid"
         ORDER BY SUM("price") DESC
      ) T
WHERE ROWNUM <= 1      

答案 1 :(得分:0)

您需要按customer_id分组以获取每个客户的所有价格。 然后对这些价格求和,然后用max(sum(price))对其进行过滤,或者按sum(price)的降序获得第一行。

-对于Oracle

select * from (Select c.name,c.id,sum(o.price) from Customer c
inner join order o on o.customer_id=c.id
group by c.name,c.id
order by sum(o.price)desc
)where rownum =1

-对于sql server和mysql

Select top 1 c.name,c.id,sum(o.price) from Customer c
inner join order o on o.customer_id=c.id
group by c.name,c.id
order by sum(o.price)desc