2014-01-17 42 views
2

我試圖做一個Group By另一個Group By的總和。如何按另一組的總和進行分組?

在LINQ中執行此操作的正確方法是什麼?

下面的查詢不起作用,但它旨在演示我想要實現的邏輯。

from so in TblServiceOrders 
join sologs in TblSOLogs on so.SONumber equals sologs.SONumber 

where so.DateClosed >= new DateTime(2014,01,17) 
where so.DateClosed <= new DateTime(2014,01,17) 
where sologs.ElapsedHours != 0 || sologs.ElapsedMinutes != 0 

group new {sologs.ElapsedHours, sologs.ElapsedMinutes} by sologs.SONumber into g 
group new {g.Sum (x => x.ElapsedHours), g.Sum (x => x.ElapsedMinutes)} by "Totals" into t 

select new { 
AverageHours = t.Average (x => x.ElapsedHours) 
AverageMins = t.Average (x => x.ElapsedMinutes) 
} 
+0

可能重複[LINQ如何顯示在所有的GroupBy結果的平均值(http://stackoverflow.com/問題/ 21181696/linq-how-to-show-average-of-all-group-groupby) – Zache

+1

不重複,不同範圍,不同問題。 –

回答

0

我已經在下面的查詢工作。現在下一個謎就是爲什麼我不能用它來填充VS中的DataGridView。 :-(

工作查詢:

from so in TblServiceOrders 
join sologs in TblSOLogs on so.SONumber equals sologs.SONumber 

where so.DateClosed >= new DateTime(2014,01,17) 
where so.DateClosed <= new DateTime(2014,01,17) 
where sologs.ElapsedHours != 0 || sologs.ElapsedMinutes != 0 

group new {sologs.ElapsedHours, sologs.ElapsedMinutes} by sologs.SONumber into g 
group new {hours = g.Sum (x => x.ElapsedHours), mins = g.Sum (x => x.ElapsedMinutes)} by "Totals" into t 

select new { 
Average = t.Average (x => (x.hours * 60) + x.mins), 
Count = t.Count() 
} 

注:

hours = g.Sum (x => x.ElapsedHours), mins = g.Sum (x => x.ElapsedMinutes) 
相關問題