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

时间:2016-04-19 22:09:17

标签: sql-server having

我有一个计算所有唯一[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

1 个答案:

答案 0 :(得分:3)

您可能需要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会将计数限制为您传递给count函数的列的唯一值。因此,当您将其作为NumberOfOrdersMade别名时,使用 orderid 列而不是customerid更有意义。