linq lambda 分组获取数据:比如数据库设计如下:
ID Salary DateTime
1 1000 2015-08-16
1 2000 2015-08-16
1 3000 2015-07-16
1 4000 2015-07-16
2 1000 2014-08-16
2 2000 2014-08-16
2 3000 2014-07-16
2 4000 2015-07-16
想得到的数据是:每个ID对应DateTime字段最大时间的全部数据, 如上面的数据得到的结果为
ID Salary DateTime
1 1000 2015-08-16
1 2000 2015-08-16
2 1000 2014-08-16
2 2000 2014-08-16
使用linq lambda 该如何获取数据????或者SQL语句该怎么写呢???
Table_2s .Join ( Table_2s .GroupBy (a => a.ID) .Select ( g => new { Key = g.Key, Max = g.Max (n => n.DateTime) } ), t => t.ID, r => r.Key, (t, r) => new { t = t, r = r } ) .Where (temp0 => (temp0.t.DateTime == temp0.r.Max)) .Select (temp0 => temp0.t)
SQL语句:
1 select S.* from (select ID,MAX([Datetime]) [Datetime] from T_Salary group by ID) T inner join T_Salary S on S.ID=T.ID and S.DateTime = T.Datetime order by ID