SQL MAX SELECT COUNT Quetion

时间:2017-08-22 01:13:01

标签: sql select count

数据库如

id    order_no
1     O1    
1     O2
2     O3
2     O4
3     O5

我希望找到最有订单的人 答案应该是

id    max(count)
1     2
2     2

这是我的SQL

select order_user, MAX(times)
from (select order_user, count(order_user) AS times
      from labt04
      group by order_user);

但它不会提醒单个组功能 有谁知道如何纠正它?

3 个答案:

答案 0 :(得分:3)

在ANSI标准SQL中,您将使用rank()

select order_user, times
from (select order_user, count(*) AS times,
             rank() over (order by count(*) desc) as seqnum
      from labt04
      group by order_user
     )
where seqnum = 1;

答案 1 :(得分:3)

如果您使用的是SQL Server,则可以使用Common Table Expression来获得所需内容:

WITH my_cte (my_id, times)
AS
(
    SELECT      my_id, COUNT(*)
    FROM        labt04
    GROUP BY    my_id
)
SELECT      my_id, times
FROM        my_cte
WHERE       times = (SELECT MAX(times) FROM my_cte)

答案 2 :(得分:1)

您可以在SQL中使用多个CTE + ROW_NUMBER() + MAX()语句,如下所示:

它会比top clause

;WITH Order_CTE_Row_Number_By_Id
AS
(
    SELECT      id, 
                Row_NUmber() over (Partition by id order by id) AS rowNumber_Id,
                order_no
    FROM        labt04
),
Order_CTE_Max_By_rowNumberById
AS
(
    SELECT      id, 
                Max(rowNumber_Id) over (order by rowNumber_Id desc) AS maxNumber_RowNumber_Id,
                rowNumber_Id,
                order_no
    FROM        Order_CTE_Row_Number_By_Id
)
SELECT  id, maxNumber_RowNumber_Id AS 'max(count)'
FROM    Order_CTE_Max_By_rowNumberById
WHERE   rowNumber_Id = maxNumber_RowNumber_Id