我正在尝试使用GroupBy在LINQ上进行查询,在Select语句中我尝试创建某种子查询。这个想法是我有7天的时间来寻找,我需要获得过去7天的平均值,但也需要获得当天的当前值。所以我尝试了以下代码:
var oDate = DateTime.UtcNow;
var startDate = oDate.AddWorkingDays(-7);
var endDate = oDate.AddWorkingDays(-1);
var races = RaceTimes.Where(
x =>
x.ODate >= startDate && x.ODate <= oDate && x.Status == "Finished")
.GroupBy(x => x.Athletes.Name).Select(x => new
{
Name = x.Key,
Description = "Just a Random Description for now",
ODate = oDate,
SevenDaysAvg = (int?)x.Where(y => y.ODate >= startDate && y.ODate <= endDate).Average(y => SqlFunctions.DateDiff("s", y.StartTime, y.EndTime)),
RaceTime = (int?)x.Where(y => y.ODate == oDate).Average(y => SqlFunctions.DateDiff("s", y.StartTime, y.EndTime))
}).ToList().Where(x => x.RaceTime!= null).ToList();
SevenDaysAvg(平均值)工作正常,它返回我过去7天比赛的平均值。但是,Latency总是返回null。
我正在尝试从SQL中翻译我的查询,这很好用:
...
AVG(case when h.ODate BETWEEN '20140219' AND '20140227' then DATEDIFF(SECOND, h.StartTime, h.EndTime) else null end) AS SevenDaysAvg,
AVG(case when h.ODate = '20140227' then DATEDIFF(SECOND, h.StartTime, h.EndTime) else null end) AS RaceTime,
...
那么我在LINQ查询中做错了什么?我这样做是不可能的?我也尝试了另一种方法。首先计算所有平均值,然后在主查询中有类似的内容:
SevenDaysAvg = averages.Where(y => y.Name== x.Athletes.Name).Select(y => y.SevenDaysAvg).FirstOrDefault()
再一次,这种方法不起作用,它一直给我空洞的结果。这有什么不对吗?