Table#Appointments:
ID, Name, LocationID, Created
Currently I have:
SELECT *
FROM Appointments
WHERE Created <= @today
ORDER BY ID
The problem is, there are times when there are more than 1 rows for a given
LocationID, and in this case, I want to return the one with the most current date.
What would the query look like?
You didn’t mention what version of SQL Server you’re using – but if you’re using 2005 or newer, you can use a CTE (Common Table Expression) with the
ROW_NUMBERfunction:This CTE “partitions” your data by
LocationID, and for each partition, theROW_NUMBERfunction hands out sequential numbers, starting at 1 and ordered byCreated DESC– so the latest row getsRowNum = 1(for eachID) which is what I select from the CTE in the SELECT statement after it.