I have inherited a table with a structure something like this:
ID Name Timestamp Data
----------------------------
1 A 40 ...
2 A 30 ...
3 A 20 ...
4 B 40 ...
5 B 20 ...
6 C 30 ...
7 C 20 ...
8 C 10 ...
ID
is an identity field and the primary key and there are non-unique indexes on the Name
and Timestamp
fields.
What is the most efficient way to get the most recent record for each item name, i.e. in the table above rows 1,4 and 6 should be returned as they are the most up-to-date entries for items A,B and C respectively.
In SQL Server, we can easily select the last 10 records from a table by using the “SELECT TOP” statement. The TOP clause in SQL Server is used to control the number or percentage of rows from the result. And to select the records from the last, we have to arrange the rows in descending order.
To get the last updated record in SQL Server: We can write trigger (which automatically fires) i.e. whenever there is a change (update) that occurs on a row, the “lastupdatedby” column value should get updated by the current timestamp.
To get the last record, the following is the query. mysql> select *from getLastRecord ORDER BY id DESC LIMIT 1; The following is the output. The above output shows that we have fetched the last record, with Id 4 and Name Carol.
SQL Server 2005 (onwards):
WITH MostRecentRows AS
(
SELECT ID, Name, Data,
ROW_NUMBER() OVER (PARTITION BY Name ORDER BY TimeStamp DESC) AS 'RowNumber'
FROM MySchema.MyTable
)
SELECT * FROM MostRecentRows
WHERE RowNumber = 1
Assuming there are no duplicate timestamps per name, something like this should work:
SELECT ID, Name, Timestamp, Data
FROM test AS o
WHERE o.Timestamp = (SELECT MAX(Timestamp)
FROM test as i
WHERE i.name = o.name)
SQL Server 2000:
SELECT
ID, Name, Timestamp, Data
FROM
DataTable
INNER JOIN
(
SELECT ID, MAX(Timestamp) Timestamp FROM DataTable GROUP BY ID
) latest ON
DataTable.ID = Latest.ID AND
DataTable.Timestamp = Latest.Timestamp
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With