简体   繁体   中英

SELECT the customer who has ordered the greatest quantity of Products in the case of two customers

I have the following ORDERS table

在此处输入图片说明

I know query to select the customer that has ordered the greatest quantity. However, how would it work, if say, two customers have the same quantity. What query should I write to show both the customers?

You can use a subquery which checks that the quantity for a given record matches the largest quantity observed in the table:

SELECT *
FROM yourTable
WHERE qty = (SELECT MAX(qty) FROM yourTable)

This will return multiple records if there are more than one customer sharing the maximum quantity.

If you only wanted to get back a single record, even in the presence of ties, you could use this approach:

SELECT *
FROM yourTable
ORDER BY qty DESC
LIMIT 1

I think you want sum of qty per custNum.

If so you can try like:

select custNum,
    sum(qty) as qty
  from Orders 
  group by custNum
  order by sum(qty) desc;

Fiddle here:

http://sqlfiddle.com/#!9/47931b/10

SELECT custnum,sum(qty) as total
FROM orders
group by custnum
having sum(qty) = (SELECT MAX(qty) FROM orders);

This will return both values.

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