drop table #abc CREATE TABLE #ABC ( CompnayID INT, TrainingCompanyID INT, CategoryID INT, ItemID INT, LastTrainedBy VARCHAR(40), LastTrainedOn DATETIME ) INSERT INTO #ABC VALUES (1, 1, 4, 2, NULL, '2013-06-18 18:06:06.737') INSERT INTO #ABC VALUES (1, 1, 4, 1, 'Test Acc', '2013-06-18 18:05:22.720') INSERT INTO #ABC VALUES (1, 1, 5, 2, 'Test Acc', '2013-06-18 18:06:06.737') INSERT INTO #ABC VALUES (1, 1, 5, 1, nULL, '2013-06-18 18:05:22.720') SELECT ROW_NUMBER() OVER (PARTITION BY TrainingCompanyID, CompnayID, CategoryID ORDER BY LastTrainedOn DESC) RN, CompnayID, TrainingCompanyID, ItemID, CategoryID, LastTrainedBy, LastTrainedOn from #ABC --Required Output -- Per Category, if there is value of LastTraiedBy then LastTrainedBy with recent LastTrainedOn date, if no value of LastTrainedBy Per Category, then recent LastTrainedOn --2 1 1 1 4 Test Acc 2013-06-18 18:05:22.720 --1 1 1 2 5 Test Acc 2013-06-18 18:06:06.737
Thanks, Cool Mind -- If you find my answer helpful, please mark it as Answer.