简体   繁体   English

选择在两个客户的情况下订购最多产品的客户

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

I have the following ORDERS table我有以下 ORDERS 表

在此处输入图片说明

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.我认为您想要每个 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 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.这将返回两个值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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