【问题标题】:Group record by hour in Enity Framwork and fill gaps在实体框架中按小时分组记录并填补空白
【发布时间】:2014-02-28 12:34:10
【问题描述】:

Grouping records hour by hour or day by day and filling gaps with zero or nullGrouping records hour by hour or day by day and filling gaps with zero or null in mysql 之前有一个类似的问题,但两者都使用SQL。我想用代码解决这个问题。

最简单的解决方案是运行:

var q = from i in XXX.Table
    let dt = p.Date
    group i by new { y = dt.Year, m = dt.Month, d = dt.Day, h = dt.Hour}
    select g;

但我还有很多空白要填补。

【问题讨论】:

  • 这个查询会被组合成另一个查询,还是我们可以假设这个(和填充的空白)将被实现?换句话说,服务器是否必须生成填充?
  • 你的实体框架可以把p.Date翻译成SQL吗?
  • @casperOne 我喜欢将此查询用作子查询,所以答案是肯定的,服务器应该生成填充
  • @SergeyBerezovskiy 我认为是的。 DateTime 类型的 EF + SQL Server 我从来没有遇到过问题
  • @SergeyBerezovskiy 你是对的,我没有检查就写了这段代码:)

标签: c# entity-framework entity-framework-6


【解决方案1】:

您可以从服务器获取组并在客户端填补空白:

var startDate = new DateTime(2014, 1, 2);
var endDate = new DateTime(2014, 1, 3);

var dict = (from c in YourTable
  where c.YourDate >= startDate && c.YourDate <= endDate 
  let hours = DbFunctions.DiffHours(startDate, c.YourDate)
  group c by hours into g 
  select new {Hour = g.Key, Count = g.Count()}).ToDictionary(r => r.Hour.Value, r => r.Count);

var result = Enumerable.Range(0, (int)(endDate - startDate).TotalHours).Select(h => new {Date = startDate.AddHours(h), Count = dict.ContainsKey(h) ? dict[h] : 0});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多