这是数据
id code status
1 1 5
2 1 6
3 2 8
4 2 9
5 2 12
6 3 15
7 3 19
8 3 13
我需要的是:
id code status
2 1 6
5 2 12
8 3 19
换句话说,我需要在代码分组时使用max id的行。
例如,对于代码3,id为6,7,8,我需要8行。
等效的SQL查询将是
select *
from t inner join (select max(id) maxId from t group by code) t1
on t.id = t1.maxId
状态列是相关的,它只是一个属性。
这样的linq查询是什么?
提前致谢。
答案 0 :(得分:3)
from t in mytable
where !(from tt in mytable
where tt.code == t.code &&
tt.id > t.id
select tt
).Any()
select t
答案 1 :(得分:1)
Literal pick-a-winner
from row in rows
group row by row.code into g
let winner =
(
from groupedrow in g
order groupedrow by groupedrow.id desc
select groupedrow
).First()
select winner;
更传统的选择胜利者(没有机会进行自动组元素获取往返)
var subquery =
from row in rows
group row by row.code into g
select new {Code = g.Key, Id = g.Max(row => row.Id)};
var query =
from row in rows
join key in subquery on new{row.Code, row.Id} == key
select row;
与发布的sql完全匹配:
IQueryable<int> subquery =
from row in rows
group row by row.code into g
select g.Max(row => row.Id);
var query =
from row in rows
join key in subquery on row.Id == key
select row;