【问题标题】:Why doesn't this query result change when DISTINCT keyword is used?为什么使用 DISTINCT 关键字时这个查询结果没有变化?
【发布时间】:2012-05-02 14:30:36
【问题描述】:

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

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。我说的对吗?

【问题讨论】:

    标签: sql distinct


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      这就是查询执行的工作方式。在您的第二个语句中,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
      

      【讨论】:

      • 正确,除了 “在 ContactTitle 列上添加 DISTINCT”DISTINCT 应用于整行,而不是列。
      • 感谢您的插图。你如何理解查询执行计划?
      • 短篇小说(无耻广告):SELECT: order or processing
      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-03-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-12-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多