Are these two queries the same - GROUP BY vs. DISTINCT?

前端 未结 8 1813
無奈伤痛
無奈伤痛 2021-01-05 07:38

These two queries seem to return the same results. Is that coincidental or are they really the same?

1.

SELECT t.ItemNumber,
  (SELECT TOP 1 ItemDes         


        
8条回答
  •  长情又很酷
    2021-01-05 08:40

    Your example #2 had me scratching me head for a while - I thought to myself: "You can't DISTINCT a single column, what would that mean?" - until I realised what is going on.

    When you have

    SELECT DISTINCT(t.ItemNumber)
    

    you are not, despite appearances, actually asking for distinct values of t.ItemNumber! Your example #2 actually gets parsed the same as

    SELECT DISTINCT
      (t.ItemNumber)
      ,
      (SELECT TOP 1 ItemDescription
       FROM Transactions
       WHERE ItemNumber = t.ItemNumber
       ORDER BY DateCreated DESC) AS ItemDescription
    FROM Transactions t
    

    with syntactically-correct but superfluous parentheses around t.ItemNumber. It is to the result-set as a whole that DISTINCT applies.

    In this case, since your GROUP BY groups by the column that actually varies, you get the same results. I'm actually slightly surprised that SQL Server doesn't (in the GROUP BY example) insist that the subqueried column is mentioned in the GROUP BY list.

提交回复
热议问题