Home > Mobile >  Linq SQL with Select MAX Sub Query
Linq SQL with Select MAX Sub Query

Time:12-13

I have the following SQL query which has a sub query so that only the max value is in the result set:

Select 
t.ID,
r.ResultIdentifier,
p.ProductID,
r.Status,
r.Start
from Result r , Transact t, Product p
WHERE r.ResultIdentifier =  (Select MAX(r2.ResultIdentifier) from Result r2 
                            where r2.Status = 'Fail'
                            and r2.ID = r.ID
                            and r2.Start >= getdate() - 30)

and r.ID = t.ID
and p.productID = 9
and t.productID = p.productID

I'm trying to convert this to a LINQ query

var failures = from result in db.Results
               join transact in db.Transacts on result.ID equals transact.ID
               join product in db.Products on transact.ProductID equals product.ProductID
               where result.ResultIdentifier == ??
               .....
               select new{ ID = transact.ID,
               ...etc

I'm really struggling with the max ResultIdentifier in the LINQ - tried multiple variations with .MAX() but cant seem to get it right.Any suggestions welcome.

CodePudding user response:

You can use the max keyword, Sorry for using method syntax as I can see you are using query :(

Should look something like the following

where result.ResultIdentifier == (Results.Max().Where(x => x.Status.equals("Fail") && x.id == result.id && x.start => Datetime.Now().Add(-30)).Select(x => x.ResultIdentifier))

CodePudding user response:

Try the following query:

var results = db.Results;
var failedResults = results
    .Where(r => r.Status == "Fail" && r.Start >= DataTime.Date.AddDays(-30));

var failures = 
    from result in results
    join transact in db.Transacts on result.ID equals transact.ID
    join product in db.Products on transact.ProductID equals product.ProductID
    from failed in failedResults
        .Where(failed => failed.ID == result.ID)
        .OrderByDescending(failed => failed.ResultIdentifier)
        .Take(1)
    where result.ResultIdentifier == failed.ResultIdentifier
    .....
    select new{ ID = transact.ID,
    ...etc
  • Related