Linq查询未返回前6个月

时间:2016-01-24 02:59:20

标签: c# linq

我有一个linq查询返回前12个月就好了

var Last12query = from ech in this.dbContext.EmployeeCheckHistories
                          where ech.CompanyID == GlobalVariables.CompanyID &&
                          ech.Employees.ClientID == GlobalVariables.Client
                          group ech by ech.CheckDate.Value.AddMonths(-12).Month into echG
                          orderby echG.Key ascending
                          select echG;

但是当我试图拉动前6个月时,它会返回相同的数据

var Last6query = from ech in this.dbContext.EmployeeCheckHistories
                          where ech.CompanyID == GlobalVariables.CompanyID &&
                          ech.Employees.ClientID == GlobalVariables.Client
                          group ech by ech.CheckDate.Value.AddMonths(-6).Month into echG
                          orderby echG.Key ascending
                          select echG;

我不确定为什么返回的数据仍然是12个月的价值。

这是我回来的JSON

[{"SeriesName":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],"Value":[160536.62000,115787.74000,300994.32000,72237.43000,73189.97000,61357.57000,43790.03000,31074.86000,58405.69000,64351.36000,82715.84000,78962.98000]},
{"SeriesName":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],"Value":[43790.03000,31074.86000,58405.69000,64351.36000,82715.84000,78962.98000,160536.62000,115787.74000,300994.32000,72237.43000,73189.97000,61357.57000]}]

2 个答案:

答案 0 :(得分:1)

您似乎没有过滤查询(where子句)只是分组,因此您始终可以获得按月分组的所有行。 从一年前的同一个月的日期中减去12个monts,所以在你的情况下,当你只得到分组的月份数时,它没有任何效果。

如果你想要从今天起最后N个月的数据,你应该有这样的东西:

var dateLimit = DateTime.Today().AddMonths(-N);
...
where ech.CheckDate>=dateLimit
group ech by ech.CheckDate.Month()
...

答案 1 :(得分:1)

通过为Last12queryLast6query编写的Linq,使用Group by是错误的,在Last6query的查询中,您刚刚将数据移至6个月前。不是本月的数据(你不会得到任何特定月份的正确数据),对于12个月的数据,它会没问题,因为你把它改了一年。您可以在数据中看到这一点。因为december-6 monthsjune,所以(任何月份 - 6个月)将是一个月。

因此,减去月份不是解决方案,请执行此查询。

var Last6query = from ech in this.dbContext.EmployeeCheckHistories
                      where ech.CompanyID == GlobalVariables.CompanyID &&
                      ech.Employees.ClientID == GlobalVariables.Client
                      where ech.CheckDate.Value.Month>DateTime.Today().AddMonths(-6)
                      group ech by ech.CheckDate.Value.Month into echG
                      orderby echG.Key ascending
                      select echG;

并在12个月内做同样的事情。因为你没有用月和年检查,否则它会显示年份错误(如果年份是2015年,它将显示2014年的结果)。

  var Last12query = from ech in this.dbContext.EmployeeCheckHistories
                      where ech.CompanyID == GlobalVariables.CompanyID &&
                      ech.Employees.ClientID == GlobalVariables.Client
                      where ech.CheckDate.Value.Month>DateTime.Today().AddMonths(-12)
                      group ech by ech.CheckDate.Value.Month into echG
                      orderby echG.Key ascending
                      select echG;