通過

2013-04-11 46 views
0

我有這個表通過

EquipmentId Value Date 
1   2  11/04/2013 
1   1  11/04/2013 
2   3  11/04/2013 
2   2  10/04/2013 
2   5  10/04/2013 
3   1  10/04/2013 
3   3  11/04/2013 

我希望將這些項目按日期得到MAXS組的總和,並有字典的日期作爲鍵和所有的MAXS的總和在當天的設備值

的結果會是這樣

[10/04/2013: 6] // 6 = 5 (as the max of values of the the equipmetId 2) + 1 (as the max of values of the the equipmetId 3) 
[11/04/2013: 5] // 5 = 2(as the max of values of the the equipmetId 1) + 3(as the max of values of the the equipmetId 3) 

我設法讓查詢得到這個不和,意爲只有一臺設備。

var consumptionValues = (from c in context.ConsumptionSet 
         join pi in context.PropertiesInstanceSet on c.PropertiesInstanceID equals pi.PropertiesInstanceID 
         join ep in context.EquipmentPropertiesSet on pi.EquipmentPropertiesID equals ep.EquipmentPropertiesID 
         join e in context.EquipmentSet on ep.EquipmentID equals e.EquipmentID 
         where (e.EquipmentID == equipmentId && pi.ProprietesName == ProprietesName.Energy && c.Date <= DateTime.Now && c.Date >= firstDayDate) 
         group c by SqlFunctions.DatePart("weekday", c.Date) into grp 
         select new 
         { 
          dayOfWeek = (DayOfWeek)grp.Key.Value - 1, 
          value = grp.Max(c => c.Value), 
         }).ToDictionary(c => c.dayOfWeek.ToString(), c => c.value); 

這是對所有連接的完整查詢,在這個例子中我給了一個簡單的例子。

是否可以在單個查詢中執行此操作?

+0

是否LINQ到實體或LINQ to SQL的? – MarcinJuraszek 2013-04-11 19:22:24

回答

0

我不得不說,我不知道它會工作,但你應該給它一個鏡頭:

var consumptionValues = (from c in context.ConsumptionSet 
         join pi in context.PropertiesInstanceSet on c.PropertiesInstanceID equals pi.PropertiesInstanceID 
         join ep in context.EquipmentPropertiesSet on pi.EquipmentPropertiesID equals ep.EquipmentPropertiesID 
         join e in context.EquipmentSet on ep.EquipmentID equals e.EquipmentID 
         where (e.EquipmentID == equipmentId && pi.ProprietesName == ProprietesName.Energy && c.Date <= DateTime.Now && c.Date >= firstDayDate) 
         group new { c, e } by SqlFunctions.DatePart("weekday", c.Date) into grp 
         select new 
         { 
          dayOfWeek = (DayOfWeek)grp.Key.Value - 1, 
          value = grp.GroupBy(i => i.e.EquipmentID).Sum(g => g.Max(i => i.c.Value)), 
         }).ToDictionary(c => c.dayOfWeek.ToString(), c => c.value); 
+0

OMG你剛剛做了我的一天。我真的沒有得到你的代碼,但它的工作原理!非常感謝 – kbaccouche 2013-04-11 19:36:32