I'm using LINQ and I trying to select rows in which the "version" column is max for EVERY "CaseId".
This is an example table with data:
╔═════════╦══════════╦═════════╦══════════╗
║ Id ║ CaseId ║ Version ║ ParentId ║
╠═════════╬══════════╬═════════╬══════════╣
║ 1 ║ A ║ 0 ║ ║
║ 2 ║ A ║ 1 ║ 1 ║
║ 3 ║ A ║ 2 ║ 2 ║
║ 4 ║ B ║ 0 ║ ║
║ 5 ║ B ║ 1 ║ 4 ║
║ 6 ║ C ║ 0 ║ ║
╚═════════╩══════════╩═════════╩══════════╝
The desired result would be:
╔═════════╦══════════╦═════════╦══════════╗
║ Id ║ CaseId ║ Version ║ ParentId ║
╠═════════╬══════════╬═════════╬══════════╣
║ 3 ║ A ║ 2 ║ 2 ║
║ 5 ║ B ║ 1 ║ 4 ║
║ 6 ║ C ║ 0 ║ ║
╚═════════╩══════════╩═════════╩══════════╝
The LINQ I'm using is the following:
IEnumerable<Case> list =
(from c in db.DBCases
let maxVersion = db.DBCases.Max(c => c.Version)
where (c.Version == maxVersion)
orderby c.CaseId descending
select c);
This is currently returning only the row with the max version of the WHOLE table, but is omitting all the other records.
╔═════════╦══════════╦═════════╦══════════╗
║ Id ║ CaseId ║ Version ║ ParentId ║
╠═════════╬══════════╬═════════╬══════════╣
║ 3 ║ A ║ 2 ║ 2 ║
╚═════════╩══════════╩═════════╩══════════╝