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
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)