使用函数的SQL查询 - 如何获取列表的最大计数

时间:2011-04-20 03:40:41

标签: mysql sql

如何查询MAXIMUM COUNT个交易次数... 我的代码如下:

SELECT customer_id, COUNT(customer_id)
FROM rental
GROUP BY customer_id
HAVING MAX(COUNT(customer_id)); //I need to get the MAXIMUM COUNT of the list

4 个答案:

答案 0 :(得分:3)

如果您要查找customer_id表中行数最多的rental,可以使用:

SELECT customer_id, COUNT(customer_id) as CustomerRowCount
FROM rental
GROUP BY customer_id
ORDER BY COUNT(customer_id) DESC
LIMIT 1

上述查询将计算每个customer_id的所有记录,按降序对它们进行排序,然后仅选择顶行。客户的最大数量将出现在CustomerRowCount

修改
康拉德提出两点或多点customer_id可能具有相同数量的记录。如果业务要求是在这种情况下应该返回多个记录,那么他的查询将为您提供您正在寻找的结果。如果只返回一条记录,那么打破关系的简单,一致的方法就是让用户具有最低的customer_id。为此,您只需将ORDER BY语句更改为:

ORDER BY COUNT(customer_id) DESC, customer_id

答案 1 :(得分:3)

尝试:

SELECT customer_id, MAX(COUNT(customer_id))
FROM rental
GROUP BY customer_id;

SELECT top 1 customer_id, COUNT(customer_id)
FROM rental
GROUP BY customer_id
ORDER BY COUNT(customer_id) DESC

答案 2 :(得分:2)

查询MySQL

SELECT 
  *
FROM (SELECT 
        customer_id, 
        COUNT(customer_id) AS CountOfCustomer
      FROM rental
      GROUP BY customer_id) q1
ORDER BY CountOfCustomer DESC
LIMIT 1

答案 3 :(得分:2)

由于多个客户可以拥有相同的最大计数,您应按照以下步骤进行操作

SELECT customer_id, 
       COUNT(customer_id) AS customerrowcount 
FROM   rental 
GROUP  BY customer_id 
HAVING COUNT(customer_id) = (SELECT COUNT(customer_id) 
                             FROM   rental 
                             GROUP  BY customer_id 
                             ORDER  BY COUNT(customer_id) DESC 
                             LIMIT  1) 

但是,如果您选择了任意客户,那么您应该使用rsbarro的答案