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

前端 未结 8 1725
無奈伤痛
無奈伤痛 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:37

    Same results but the second one seems to have a more expensive sort step to apply the DISTINCT on my quick test.

    Both were beaten out of sight by ROW_NUMBER though...

    with T as
    (
    SELECT ItemNumber, 
           ItemDescription,
           ROW_NUMBER() OVER ( PARTITION BY ItemNumber ORDER BY DateCreated DESC) AS RN
    FROM Transactions
    )
    SELECT * FROM T
    WHERE RN=1
    

    edit ...which in turn was thumped by Joe's solution on my test setup.

    Test Setup

    CREATE TABLE Transactions
    (
    ItemNumber INT not null,
    ItemDescription VARCHAR(50) not null,
    DateCreated DATETIME not null
    )
    
    INSERT INTO Transactions
    SELECT 
    number, NEWID(),DATEADD(day, cast(rand(CAST(newid() as varbinary))*10000 
      as int),getdate()) 
    FROM master.dbo.spt_values
    
    ALTER TABLE dbo.Transactions ADD CONSTRAINT
        PK_Transactions PRIMARY KEY CLUSTERED 
        (ItemNumber,DateCreated) 
    

提交回复
热议问题