https://data.stackexchange.com/stackoverflow/query/8495/so3358976
-- SO3358976
-- update-lastest-record-for-each-key-sql
CREATE TABLE #temp ([Key] char(3) NOT NULL
, [Value] char(3) NOT NULL
, [Date] date NOT NULL
, [Status] char(1) NOT NULL)
INSERT INTO #temp VALUES ('001', 'AAA', '2010-01-01', 'E')
,('001', 'BBB', '2010-02-01', 'E')
,('001', 'CCC', '2010-03-01', 'E')
,('002', 'XXX', '2010-04-01', 'E')
,('002', 'YYY', '2010-05-01', 'E')
,('002', 'ZZZ', '2010-06-01', 'E')
,('003', 'HHH', '2010-03-01', 'E')
,('003', 'GGG', '2010-04-01', 'E')
;WITH Latest AS (
SELECT [Key], MAX([Date]) AS LastDate FROM #temp GROUP BY [Key]
)
UPDATE t
SET [Status] = 'C'
FROM #temp AS t
INNER JOIN Latest
ON t.[Key] = Latest.[Key]
AND t.[Date] = Latest.[LastDate]
SELECT * FROM #temp