考虑一个用于存储审核事件的SQL Server表。
需要为每个CustID仅获取最新条目。我们想要获得整个对象/行。我假设在查询中需要GroupBy()。这是迄今为止的查询:
var custsLastAccess = db.CustAccesses
.Where(c.AccessReason.Length>0)
.GroupBy(c => c.CustID)
// .Select()
.ToList();
// (?) where to put the c.Max(cu=>cu.AccessDate)
问题:
如何创建查询以选择每个AccessDate
的最新(CustID
}个最大记录/对象?
答案 0 :(得分:33)
我想知道是否有:
var custsLastAccess = db.CustAccesses
.Where(c.AccessReason.Length>0)
.GroupBy(c => c.CustID)
.Select(grp => new {
grp.Key,
LastAccess = grp
.OrderByDescending(x => x.AccessDate)
.Select(x => x.AccessDate)
.FirstOrDefault()
}).ToList();
您还可以尝试OrderBy()
和Last()
答案 1 :(得分:21)
使用LINQ语法,我觉得它看起来更干净:
var custsLastAccess = from c in db.CustAccesses
group c by c.CustID into grp
select grp.OrderByDescending(c => c.AccessDate).FirstOrDefault();
答案 2 :(得分:4)
这里:这使用max而不是OrderByDesc,所以应该更有效率。
var subquery = from c in CustAccesses
group c by c.CustID into g
select new
{
CustID = g.Key,
AccessDate = g.Max(a => a.AccessDate)
};
var query = from c in CustAccesses
join s in subquery
on c.CustID equals s.CustID
where c.AccessDate == s.AccessDate
&& !string.IsNullOrEmpty(c.AccessReason)
select c;
答案 3 :(得分:0)
var custsLastAccess = db.CustAccesses
.Where(c.AccessReason.Length>0)
.GroupBy(c => c.CustID, (id, custs) => new { ID=id, LastAccess=custs.OrderByDescending(c=>c.AccessDate).First().AccessDate})
.Select()
.ToList();