使用Select MAX子查询的Linq SQL

jyztefdp  于 2022-12-15  发布在  其他
关注(0)|答案(2)|浏览(167)

我有下面的SQL查询,它有一个子查询,所以结果集中只有最大值:

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

我正在尝试将其转换为LINQ查询

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

我真的很纠结于LINQ中的最大结果标识符--尝试了.MAX()的多个变体,但似乎都做不对。欢迎提出任何建议。

hec6srdp

hec6srdp1#

您可以使用max关键字,抱歉使用方法语法,因为我可以看到您正在使用query:(
应如下所示

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

ao218c7q2#

请尝试以下查询:

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

相关问题