将group by和MAX转换为Linq

时间:2013-04-16 13:06:54

标签: sql linq entity-framework

我在sql中创建了以下查询,但我无法找到如何在我的linq中实现StatusAndTrackingNotes表连接:

SELECT *
FROM [Application] APP
join User USR on APP.ApplicationId = USR.UserApplicationId
join 
(Select MAX(TrackingDate) as MaxDateTD,TrackingApplicationId
 From StatusAndTrackingNotes 
 where TrackingLoanType = 1 and ((TrackingStatusCode <= 52 and TrackingStatusCode >= 50) or TrackingStatusCode = 62)
 group by TrackingApplicationId) MTND on APP.ApplicationId = MTND.TrackingApplicationId
join Details DTL on APP.ApplicationId = DTL.ApplicationId
join ApplicationFees AF on APP.ApplicationId = AF.ApplicationId
where APP.LatestStatus = 'F' and DTL.Type = 1 and DTL.FundingDate >= '2011-06-01'  and   DTL.FundingDate <= '2013-06-30'
    and AF.FirstRefPaidDate is not null

请帮助我使用语法。首先,我使用简单查询和连接,然后

([Linq Query]).GroupBy(i => i.TrackingApplicationId).Select(g => g.OrderByDescending(c => c.TrackingDate).FirstOrDefault());

但它不会返回任何结果。请帮助。 提前致谢

1 个答案:

答案 0 :(得分:1)

我会通过创建StatusAndTrackingNotes作为单独的查询并加入并将其分组到“主查询”来解决它。即:

var trackingQuery =
    from t in statusAndTrackingNotes
    where t.TrackingLoanType == 1 && (t.TrackingStatusCode <= 52 && t.TrackingStatusCode >=50) || t.TrackingStatusCode == 62
    group t by t.TrackingApplicationId into trackings
    select new 
    { 
        TrackingApplicationId = trackings.Key,
        MaxDate = trackings.Max(t => t.TrackingDate)
    };

var appQuery =
    from app in Application
    join t in trackingQuery on app.ApplicationId equals t.TrackingApplicationId
    /* other joins here */
    select new
    {
        app,
        t.MaxDate,
    };