我有一个名为Consult的sql表,它代表物理治疗师的咨询(治疗)
ConsultID ConsultDate Therapist Location
我想提供每周汇总的数据,从28周前开始直到本周
像:
Location Week-1 Week-2 Week-3 ..... Week-28
Amsterdam 41 38 34 55
Utrecht 65 56 46 46
我如何在Linq中执行此操作?我有以下内容:
public ActionResult Therapist(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
DateTime startDate = DateTime.Now.StartOfWeek(DayOfWeek.Monday).AddDays(-168);
DateTime endDate = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);
var TherapistConsult = from row in db.Consults
where ((row.Therapist == id) && (row.ConsultDate > startDate) && (row.ConsultDate < endDate))
group row by row.Location into g
where g.FirstOrDefault() != null
select new
{
Location = g.Key,
// Need a loop here for 28 weeks in the past till this week
// WeekN = g.Count(x => x.Week == N),
};
return View(TherapistConsult.ToList());
}
答案 0 :(得分:0)
您正在寻找的是“透视”您的数据,这从SQL然后从linq更容易实现,
在CodeProject中查找
http://www.codeproject.com/Tips/500811/Simple-Way-To-Use-Pivot-In-SQL-Query
如果你因为某种原因 在linq中执行此操作,请查看以下内容:
Pivot data using LINQ