48

Consider a SQL Server table that's used to store events for auditing.

The need is to get only that latest entry for each CustID. We want to get the entire object/row. I am assuming that a GroupBy() will be needed in the query. Here's the query so far:

var custsLastAccess = db.CustAccesses   
                        .Where(c.AccessReason.Length>0)
                        .GroupBy(c => c.CustID)
//                      .Select()
                        .ToList();
// (?) where to put the c.Max(cu=>cu.AccessDate) 

Custs Layout

Question: How can I create the query to select the latest(the maximum AccessDate) record/object for each CustID?

3 Answers 3

49

I'm wondering if something like:

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();

you could also try OrderBy() and Last()

1
  • Thanks Marc Gravell It is very useful . Aug 7, 2018 at 7:11
31

Using LINQ syntax, which I think looks cleaner:

var custsLastAccess = from c in db.CustAccesses 
                      group c by c.CustID into grp
                      select grp.OrderByDescending(c => c.AccessDate).FirstOrDefault();
0
7

Here: this uses max rather than OrderByDesc, so should be more efficient.

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;
4
  • 3
    Be aware that this won't break ties - if there are two rows with the same CustID and the same AccessDAte, they will both be found in the join, and you might end up with multiple "most recent accesses" per customer id. Sep 10, 2013 at 18:51
  • @DanielYankowsky i hadn't run into that. Would a Distinct on the end resolve that?
    – Gary
    Feb 14, 2019 at 14:09
  • @Gary no you really need another discriminator in your max check. Ideally the FirstOrDefault answer has a sub ordering of something like record ID for example so the result is consistent.
    – Shiv
    Jun 6, 2022 at 3:31
  • This one worked for me and correctly only executed once SQL query. The other answers in this thread gave errors saying the GroupBy was not able to be translated. This was due to calling methods on GroupBy afterwards, like OrderByDesc. I was however able to call distinct, hence to avoid the duplication mentioned in above comments use .. subquery.Distinct() ..
    – schwartz
    Jan 25 at 13:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.