I have a history table for Students in SQL Server 2008.
StudentHistoryId, StudentId, Grade, CreatedAt, ModifiedAt, ModifiedBy, Active
How do I write a tsql query to get the latest modified row for all the active students ?
Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Dorababu MekaRank #457 · 5.5K reputationPosted May 13, 2011, 7:52 PM EDT
var q = from h in history where h.Active group h by h.StudentId into g select new { StudentID = g.Key, LatestModified = g.Max (x => x.ModifiedAt) }Guest UserRank #1,422 · 1.2K reputationPosted May 14, 2011, 3:23 AM EDT
SELECT history.* FROM history
INNER JOIN
(SELECT h.StudentId, MAX(h.ModifiedAt) AS LastModified
FROM history AS h WHERE Active = 1 GROUP BY h.StudentId) Recents
ON Recents.StudentId = history.StudentId AND Recents.LastModified = history.ModifiedAt
I haven't tested this so it may need some tweaking...
Desi Gal35 reputationPosted May 16, 2011, 9:21 AM EDT
Suthish NairRank #92 · 22.8K reputationPosted May 16, 2011, 10:29 AM EDT
Desi Gal35 reputationPosted May 16, 2011, 10:32 AM EDT
Suthish NairRank #92 · 22.8K reputationPosted May 16, 2011, 10:48 AM EDT
Desi Gal35 reputationPosted May 16, 2011, 10:53 AM EDT
Select *
From Students_History SH
Where SH.Active = 1 and SH.ModifiedAt in (
select MAX(SH1.modifiedat)from Students_History SH1
group by SH1.RuleId)
Suthish NairRank #92 · 22.8K reputationPosted May 16, 2011, 11:07 AM EDT
Select *
From Students_History SH
Where SH.Active = 1 and SH.ModifiedAt in (
select MAX(SH1.modifiedat)from Students_History SH1 where SH1.Active = 1
group by SH1.RuleId)
Desi Gal35 reputationPosted May 16, 2011, 11:08 AM EDT