2011-10-13 187 views
1

我有以下的LINQ到SQL代碼LINQ到SQL - 集團通過

var customerList = from cm in dc.ConsignmentMarginBreakdowns 
        join tm in dc.ConsignmentTripBreakdowns on new { Depot = cm.Depot, TripNumber = cm.TripNumber, TripDate = cm.TripDate } equals new { Depot = tm.Depot, TripNumber = tm.TripNumber, TripDate = tm.TripDate } 
        join sl in dc.SageAccounts on new { LegacyID = cm.Customer, Customer = true } equals new { LegacyID = sl.LegacyID, Customer = sl.Customer } 
        join ss in dc.SageAccounts on sl.ParentAccount equals ss.ID 
        where (tm.DeliveryDate >= dateRange1.FromDate && tm.DeliveryDate <= dateRange1.ToDate) || (dateRange2.FromDate != null && (tm.DeliveryDate >= dateRange2.FromDate && tm.DeliveryDate <= dateRange2.ToDate)) 
        where tm.Depot == depotLetter 
        group cm by new { ss.Name, ss.ID } into cmg 
        select new 
        { 
         CustomerID = cmg.Key.ID, 
         CustomerName = cmg.Key.Name, 
         Sales1 = cmg.Where(a => a.DeliveryDate >= dateRange1.FromDate && a.DeliveryDate <= dateRange1.ToDate).Sum(a => a.TripSalesTotal), 
         Sales2 = dateRange2.FromDate != null ? tmg.Where(a => a.DeliveryDate >= dateRange2.FromDate && a.DeliveryDate <= dateRange2.ToDate).Sum(a => a.TripSalesTotal) : 0.00m 
        }; 

我的問題是,從「以舊換新」的「DeliveryDate」不在查詢範圍當我選擇。任何想法如何我可以在我的查詢中獲得這個值?

感謝

回答

1

只需創建另一個匿名類型

group new { cm, tm } by new { ss.Name, ss.ID } into cmg 

所以您的查詢應該是這樣的:

var customerList = from cm in dc.ConsignmentMarginBreakdowns 
        join tm in dc.ConsignmentTripBreakdowns on new { Depot = cm.Depot, TripNumber = cm.TripNumber, TripDate = cm.TripDate } equals new { Depot = tm.Depot, TripNumber = tm.TripNumber, TripDate = tm.TripDate } 
        join sl in dc.SageAccounts on new { LegacyID = cm.Customer, Customer = true } equals new { LegacyID = sl.LegacyID, Customer = sl.Customer } 
        join ss in dc.SageAccounts on sl.ParentAccount equals ss.ID 
        where (tm.DeliveryDate >= dateRange1.FromDate && tm.DeliveryDate <= dateRange1.ToDate) || (dateRange2.FromDate != null && (tm.DeliveryDate >= dateRange2.FromDate && tm.DeliveryDate <= dateRange2.ToDate)) 
        where tm.Depot == depotLetter 
        group new { cm, tm } by new { ss.Name, ss.ID } into cmg 
        select new 
        { 
         CustomerID = cmg.Key.ID, 
         CustomerName = cmg.Key.Name, 
         Sales1 = cmg.Where(a => a.tm.DeliveryDate >= dateRange1.FromDate && a.tm.DeliveryDate <= dateRange1.ToDate).Sum(a => a.cm.TripSalesTotal), 
         Sales2 = dateRange2.FromDate != null ? tmg.Where(a => a.tm.DeliveryDate >= dateRange2.FromDate && a.tm.DeliveryDate <= dateRange2.ToDate).Sum(a => a.cm.TripSalesTotal) : 0.00m 
        };