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 ItemDescription
FROM Transactions
WHERE ItemNumber = t.ItemNumber
ORDER BY DateCreated DESC) AS ItemDescription
FROM Transactions t
GROUP BY t.ItemNumber
2.
SELECT DISTINCT(t.ItemNumber),
(SELECT TOP 1 ItemDescription
FROM Transactions
WHERE ItemNumber = t.ItemNumber
ORDER BY DateCreated DESC) AS ItemDescription
FROM Transactions t
A bit of explanation:
I’m trying to get a distinct list of items from a table full of transactions. For each item, I’m looking for the ItemNumber (the identifying field) and the most recent ItemDescription.
Your example #2 had me scratching me head for a while – I thought to myself: “You can’t
DISTINCTa single column, what would that mean?” – until I realised what is going on.When you have
you are not, despite appearances, actually asking for distinct values of
t.ItemNumber! Your example #2 actually gets parsed the same aswith syntactically-correct but superfluous parentheses around
t.ItemNumber. It is to the result-set as a whole thatDISTINCTapplies.In this case, since your
GROUP BYgroups by the column that actually varies, you get the same results. I’m actually slightly surprised that SQL Server doesn’t (in theGROUP BYexample) insist that the subqueried column is mentioned in theGROUP BYlist.