简体   繁体   English

最大和计数查询

[英]max and count query

I'm trying to make a query with max and count like this one: (taken from http://www.w3resource.com/sql/aggregate-functions/max-count.php ) 我正在尝试使用max和count进行这样的查询:(取自http://www.w3resource.com/sql/aggregate-functions/max-count.php

SELECT MAX (mycount)   
FROM (SELECT agent_code,COUNT(agent_code) mycount   
FROM orders   
GROUP BY agent_code);  

this query returns a column with the name 'MAX(MYCOUNT)' with the max value: '7',the simple change I want is that I would like to get the agent code of the one who got the maximum, instead of the max records of agent code. 此查询返回一个名称为“ MAX(MYCOUNT)”的列,其最大值为“ 7”,我想要的简单更改是我想获取获得最大值而不是最大值的代理代码代理代码的记录。

tried to do this in some ways but no luck so far, hope you can help me to do this right. 尝试以某种方式做到这一点,但到目前为止还算不上运气,希望您能帮助我正确地做到这一点。

If you don't have to worry about a tie for two agents having the max number of orders, then you can try the following: 如果您不必担心两个具有最大订单数的业务代表的平局,则可以尝试以下操作:

SELECT agent_code, COUNT(*) AS mycount
FROM orders
GROUP BY agent_code
ORDER BY COUNT(*) DESC
LIMIT 1

If you do have to worry about a tie for the max number of orders, and you want all ties, then you can use a subquery: 如果您确实需要担心最大订单数是平局,并且想要所有平局,那么可以使用子查询:

SELECT agent_code, COUNT(*) AS mycount
FROM orders
GROUP BY agent_code
HAVING COUNT(*) = (SELECT MAX(t.mycount) FROM
                   (SELECT COUNT(*) AS mycount FROM orders GROUP BY agent_code) t)

You can use order by and limit : 您可以使用order bylimit

SELECT agent_code, COUNT(agent_code) as mycount   
FROM orders   
GROUP BY agent_code
ORDER BY mycount DESC
LIMIT 1;

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

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