linq C#中使用MAX()的子查询

zxlwwiss  于 2022-12-06  发布在  C#
关注(0)|答案(2)|浏览(146)

我可以用C#处理查询,但是我不知道如何写这个子查询。谢谢你的帮助。

SELECT * 
FROM Stores.PerformanceRealization PR
LEFT JOIN Stores.GroupRealization ON Stores.GroupRealization.Id = PR.GroupRealizationId
WHERE PR.Deadline = (SELECT MAX(Deadline) 
                     FROM Stores.PerformanceRealization PR2 
                     WHERE PR.GroupRealizationId = PR2.GroupRealizationId)

我试过这样的方法:

var result = from aa in _context.PerformanceRealization
             join bb in _context.GroupRealization on bb.Id equals aa.GroupRealizationId
             where aa.Deadline = (from cc in _context.PerformanceRealization 
                                  where aa.GroupRealizationId = cc.GroupRealizationId 
                                  select max(cc.Deadline))   
             select aa;
1tuwyuhd

1tuwyuhd1#

请尝试以下查询,这样可以避免在Deadline重复时发生冲突。

var realizations  = _context.PerformanceRealization; //  here  you can add filters

var result = 
    from aa in realizations
    join bb in _context.GroupRealization on bb.Id equals aa.GroupRealizationId into bbj
    from bb in bbj.DefaultIfEmpty() // left join
    from cc in realizations
        .Where(cc => aa.GroupRealizationId = cc.GroupRealizationId)
        .OrderByDescnding(cc => cc.Deadline)
        .Take(1) // outer apply or join to ROW_NUMBER query
    select new  
    {
        aa,
        bb
    };
fhity93d

fhity93d2#

我在这里找到了答案:LINQ SELECT with Max and Where in SUBQUERY
我的解决方案:

_context.PerformanceRealization.Where(u => u.Deadline == 
                                         _context.PerformanceRealization
                                         .Where(x => x.GroupRealizationId == u.GroupRealizationId)
                                         .Max(x => x.Deadline))
                               .Select(u => u);

相关问题