CREATE TABLE #test ( id int, ProductName VARCHAR(25) ) insert into #test select 1, 'Apple' union all select 2, 'Apple' union all select 5, 'Apple' union all select 3, 'Orange' union all select 4, 'Orange' union all select 10, 'Orange'
SELECT * FROM #test SELECT maxID FROM ( SELECT MAX(id) AS maxID, ProductName AS nn, RANK() OVER (PARTITION BY ProductName ORDER BY id DESC) AS MyRank FROM #test GROUP BY id, ProductName ) tmp WHERE tmp.MyRank = 2