我尝试使用Entity Framework和Linq to Entities编写查询,以获取表格中的每日事件计数,这些计划将用于绘图。问题是,即使没有可用的数据,我也想要返回完整的日期列表。
我找到了一个答案建议使用numbers table,这主要是有效的,但是我对左外连接有问题(这是我认为我需要做的)。
这个简单的查询返回过去7天,包括今天:
var foo = from n in Numbers
where n.NumberId > 0 && n.NumberId <= 7
let date = DbFunctions.AddDays(start, n.NumberId)
select date;
但完整的查询,我无法通过left outer join
找出正确的连接和分组语法var bar = from n in Numbers
where n.NumberId > 0 && n.NumberId <= 7
let date = DbFunctions.AddDays(start, n.NumberId)
join i in Incidents on EntityFunctions.TruncateTime(date.Value) equals EntityFunctions.TruncateTime(i.IncidentDate) into days
from day in days.DefaultIfEmpty()
group day by EntityFunctions.TruncateTime(day.IncidentDate) into g
select new {
g.Key,
Count = g.Count()
};
最终结果应该类似于:
Date | Count
-------------
3/26/2014 | 0
3/25/2014 | 10
3/24/2014 | 9
...
答案 0 :(得分:0)
我在发布后不久就解决了这个问题。解决方案是:
var bar = from n in Numbers
where n.NumberId > 0 && n.NumberId <= 7
let date = DbFunctions.AddDays(start, n.NumberId)
join i in Incidents on EntityFunctions.TruncateTime(date) equals EntityFunctions.TruncateTime(i.IncidentDate) into days
select new {
date,
Count = days.Count()
};