简体   繁体   中英

Select customer with highest price of all his orders

在此处输入图片说明 i want to list customer id with highest sum of price of his orders. Please see graph oí orders down.

SQL DEMO

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

You need to group by customer_id to get all prices of each customers. Then sum these prices filter it with max( sum(price))or get first row by descending order of sum(price).

--for 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

--For sql server and 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM