有一个显示此内容的查询...
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。
答案 0 :(得分: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
答案 1 :(得分:1)
您可以使用common table expression(或子查询)来获取细分,然后选择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])