0

有一个显示这个的查询......

salesPersonId Total
------------- -----------
AB4           3
GT10          2
JB9           1
JS1           2
KT8           4
TC3           4
VG7           2
WC2           7

(8 row(s) affected)

我的查询是...

SELECT so.salesPersonId, COUNT(so.orderId) AS 'Total'
FROM salesOrder AS so

GROUP BY so.salesPersonId
GO

我想这样做...

SELECT so.salesPersonId, COUNT(so.orderId) AS 'Total'
FROM salesOrder AS so
WHERE MAX(COUNT(so.orderId))
GROUP BY so.salesPersonId
GO

这给了我一个错误,关于如何只显示总数最高的 salesPersonId 的任何想法?这里是WC2。

4

2 回答 2

1
WITH totalCount
AS
(
    SELECT so.salesPersonId, COUNT(so.orderId) AS 'Total'
    FROM salesOrder AS so
    GROUP BY so.salesPersonId
),
maxCount AS
(
    SELECT salesPersonId, Total,
            DENSE_RANK() OVER (ORDER BY Total DESC) rn
    FROM totalCount
)
SELECT salesPersonId, Total
FROM    maxCount
WHERE rn = 1
于 2012-11-26T03:11:58.317 回答
1

您可以使用公用表表达式(或子查询)来获取细分,然后选择 CTE 中的所有条目,其中它们的总数等于最大总数(因为可能有多个):

;WITH TotalOrders
AS
    (
    SELECT so.salesPersonId, COUNT(so.orderId) AS 'Total'
    FROM salesOrder AS so
    GROUP BY so.salesPersonId
    )
SELECT *
FROM TotalOrders [TO]
WHERE [TO].Total = (SELECT MAX([TO].Total) FROM TotalOrders [TO])
于 2012-11-26T03:12:07.547 回答