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

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

结果是这样的

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

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

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

4

1 回答 1

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);
于 2013-04-11T19:25:14.137 回答