使用Linq-to-SQL进行分组后,从多个表中获取结果

时间:2012-02-15 08:29:40

标签: sql-server join linq-to-sql group-by where

我认为答案应该很简单,但我只是苦苦挣扎:

希望LINQ查询中的2个表中的数据类似于:

from f in Faults
join af in AvailabilityFaults on f.FaultID equals af.FaultID
join a in Availabilities on new { af.CalendarDay, af.CircuitNumber}
             equals new { a.CalendarDay, a.CircuitNumber}
join e in ExternalImportAvailabilities on new { a.CalendarDay, a.CircuitNumber }
                   equals new { e.CalendarDay, e.CircuitNumber }
where a.CalendarDay.Value.Day != 1
group f by f.FaultID into groupF
select new {groupF, e.CalendarDay}

这里的问题在于它在select子句中找不到e.CalendarDay

我也尝试过这样的事情:CalendarDay= e.Max(e=>e.CalendarDay),但是e不在当前的背景下。

如何在select子句中添加表'e'中的数据?

2 个答案:

答案 0 :(得分:1)

如果我理解你,那就是你要找的:

from f in Faults
join af in AvailabilityFaults on f.FaultID equals af.FaultID
join a in Availabilities on af.CalendarDay equals a.CalendarDay and af.CircuitNumber equals a.CircuitNumber
join e in ExternalImportAvailabilities on a.CalendarDay equals e.CalendarDay and a.CircuitNumber equals e.CircuitNumber
where a.CalendarDay.Value.Day != 1
group new {f, e} by f.FaultID into groupFE
select new {GroupF = groupFE.Select( gfe => gfe.f), CalendarDay = groupFE.Max( gfe => gfe.e.CalendarDay)}

答案 1 :(得分:0)

如果您想在选择中使用e.CalendarDay,那么您通常会将其包含在组中,如

group f by new { f.FaultID , e.CalendarDay } into groupF
select new {groupF.Key.FaultID, groupF.Key.CalendarDay}