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

前端 未结 8 1801
無奈伤痛
無奈伤痛 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条回答
  •  猫巷女王i
    2021-01-05 08:19

    If you're running at least 2005 and can use a CTE, this is a little cleaner IMHO.

    EDIT: As pointed out in Martin's answer, this also performs much better.

    ;with cteMaxDate as (
        select t.ItemNumber, max(DateCreated) as MaxDate
            from Transactions t
            group by t.ItemNumber
    )
    SELECT t.ItemNumber, t.ItemDescription
        FROM cteMaxDate md
            inner join Transactions t
                on md.ItemNumber = t.ItemNumber
                    and md.MaxDate = t.DateCreated
    

提交回复
热议问题