通过

2013-04-11 43 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