简体   繁体   中英

Linq SQL with Select MAX Sub Query

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM