3

为什么两次查询的结果是一样的?(我正在使用北风数据库。

SELECT      ContactTitle
        ,   COUNT(CustomerID) AS NumberOfCustomer
FROM        dbo.Customers
WHERE       ContactTitle LIKE '%sales%'
GROUP BY    ContactTitle
HAVING      COUNT(*) >= 5
ORDER BY    NumberOfCustomer desc

SELECT 
DISTINCT    ContactTitle
        ,   COUNT(CustomerID) AS NumberOfCustomer
FROM        dbo.Customers
WHERE       ContactTitle LIKE '%sales%'
GROUP BY    ContactTitle
HAVING      COUNT(*) >= 5
ORDER BY    NumberOfCustomer desc

结果是:

ContactTitle           NumberOfCustomer
---------------------  ----------------
Sales Representative         17
Sales Manager                11
Sales Associate               7
Sales Agent                   5

以我自己的理解,第二个查询获取不同的标题并计算其记录,所以我希望结果不会是因为每个标题的记录数只有 1。我说的对吗?

4

4 回答 4

7

DISTINCT在其他操作之后完成。首先,它执行 GROUP BY 已经使每一行都不同,所以DISTINCT是多余的。

于 2012-05-02T14:33:31.967 回答
3

distinct 应用于标题计数。一旦您的选择完成计算,它就会从中创建不同的列表。

于 2012-05-02T14:33:59.090 回答
3

DISTINCT将从结果集中过滤重复记录。由于在这种情况下没有重复记录,DISTINCT因此 没有效果。

于 2012-05-02T14:34:04.570 回答
3

这就是查询执行的工作方式。在您的第二条语句中,DISTINCT不执行任何附加功能,因为您GROUP BY包含相同的列名ContactTitle已经为您执行了该操作。

1. FROM
2. WHERE
3. GROUP BY <-- You have specified the column `ContactTitle`, 
-- which means the results would be grouped by that column to product unique 
--result.
4. HAVING
5. SELECT <-- Adding DISTINCT on ContactTitle column here doesn't make much 
-- difference and it is actually redundant. DISTINCT is applied to the whole
-- row but the resultset already contains distinct rows grouped by the column 
-- `ContactTitle`.
6. ORDER BY
于 2012-05-02T14:38:46.530 回答