使用DISTINCT关键字时,为什么此查询结果不会更改?

时间:2012-05-02 14:30:37

标签: sql distinct

为什么两个查询的结果相同? (我正在使用northwind数据库。

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 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:3)

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

答案 2 :(得分:3)

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

答案 3 :(得分: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