如何在Order表中获取最大计数用户的ID

时间:2016-07-12 07:24:06

标签: mysql sql

我有一张表

orderNumber(pk) , customerNumber , comment

我必须计算用户所下的最大订单并显示其用户ID和MAX计数。我有以下查询

它显示计数权限,但它需要表格中的第一个CustomerNumber

SELECT maxCount.customerNumber , MAX(`counted`) FROM
(
SELECT customerNumber, COUNT(*) AS `counted`
FROM `orders`
GROUP BY `customerNumber`
)as maxCount

谢谢&问候

1 个答案:

答案 0 :(得分:5)

只需在内部查询中使用ORDER BY

SELECT customerNumber, COUNT(*) AS `counted`
FROM `orders`
GROUP BY `customerNumber`
ORDER BY COUNT(*) DESC
LIMIT 1

如果要在平局时返回所有客户编号,可以使用带有子查询的HAVING子句来标识最大数量:

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

在这里演示:

SQLFiddle