SQL 服务器如何在 HAVING 子句中使用 COUNT DISTINCT(*)?

SQL Server how can I use COUNT DISTINCT(*) in HAVING clause?

我有一个计算所有唯一 [customerid] 值并将它们显示在 SELECT 列表中的过程。我正在尝试使用 HAVING 子句对 [customerid] 进行排序,使其仅显示“> 1”,但 SQL 不允许我在 HAVING 中使用 DISTINCT COUNT。在我看来,HAVING 应该与 COUNT 一起工作是有道理的,但事实并非如此:

USE MyCompany;
GO
SELECT DISTINCT COUNT(customerid) AS NumberOfOrdersMade, customerid AS 
CustomerID
FROM tblItems_Ordered
GROUP BY customerid
HAVING DISTINCT COUNT(customerid) > 1
GO

你可能想要 SELECT COUNT(DISTINCT orderid) 而不是 DISTINCT COUNT(customerid):

USE MyCompany;
GO
SELECT COUNT(DISTINCT orderid) AS NumberOfOrdersMade, customerid AS
CustomerID
FROM tblItems_Ordered
GROUP BY customerid
HAVING COUNT(DISTINCT orderid) > 1
GO

COUNT 之外时,DISTINCT 将从结果集中消除重复行,这对您的查询没有影响,因为您正在执行 GROUP BY。在 COUNT 内时,DISTINCT 会将计数限制为您传递给计数函数的列的唯一值。因此,当您将其别名为 NumberOfOrdersMade.

时,使用 orderid 列而不是 customerid 更有意义