得到最大组的总和

时间:2013-04-11 19:18:35

标签: linq sum

我有这张桌子

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

我想按日期对这些项目进行分组,并设置一个字典,其中日期为关键字,以及当天所有设备值的最大值之和

结果就像这样

[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);

这是包含所有连接的完整查询,在示例中我只给出了一个简化示例。

是否可以在一个查询中执行此操作?

1 个答案:

答案 0 :(得分: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);