【问题标题】:LINQ: latest sum of data within data rangeLINQ:数据范围内的最新数据总和
【发布时间】:2018-08-23 19:05:34
【问题描述】:

我的数据库中有一个快照表,其中包含预约可用性的历史数据。

我正在尝试编写一个 LINQ 查询,以获取最新快照中给定日期范围内的可用插槽总数。

这是我的桌子的样子:

因此,有了这个给定的数据,我希望我的 LINQ 查询返回 2018 年 1 月 1 日至 2018 年 1 月 2 日日期范围内的可用插槽总和以及最新的 SnapShotTime。所以,我希望查询返回 4。

这是我目前所拥有的。

var test = db.snapshots
      .GroupBy(g =>
         g.AppointmentTime >= startDate &&
         g.AppointmentTime <= endDate
      ).Select(s => s.OrderByDesending(x => x.SnapShotTime).FirstOrDefault();

但是,我不确定如何将可用插槽的总和放入此 LINQ 查询中。任何有关编写此查询的帮助将不胜感激!

【问题讨论】:

  • 你的GroupBy应该是Where,然后你应该按SnapShotTime分组并取最高组的总和。尽管我认为您应该按 SnapShotTime 的分钟或秒部分分组?它们真的可以等于毫秒吗?
  • “20:0101:137”代表什么?
  • @NetMage,这只是 DateTime 列中的时间戳
  • @GertArnold,我将如何按分钟分组?
  • 这取决于SnapShotTime的数据类型。它不常见的(对我来说)格式让我想知道它是否是 DateTime。

标签: c# entity-framework linq linq-to-sql


【解决方案1】:

我没有看到你写的确切查询,但根据你的解释,我认为这样的事情可能有用

var query=db.snapshots
              .Where(x=>x.AppointmentTime >= startDate &&
                     x.AppointmentTime <= endDate)
              .GroupBy(x=>x.SnapShotTime)
              .OrderByDesending(g=>g.Key)
              .Take(1)
              .Sum(x=>x.Value.AvailableSlots);

或者如果它看起来很复杂,你最好先得到这样的最新日期

var latest=db.snapshots
            .OrderByDesending(x => x.SnapShotTime)
            .FirstOrDefault().SnapShotTime;

然后像这样得到你的计数

var query=db.snapshots
           .Where(x=>x.AppointmentTime >= startDate &&
                     x.AppointmentTime <= endDate   &&
                     x.SnapShotTime==latest)
            .Sum(x=>x.AvailableSlots);

【讨论】:

  • Value 没有定义
  • 我最终得到了与此类似的内容,但在末尾添加了以下内容:.Sum(x => (int?)x.AvailableSlots) ?? 0.
【解决方案2】:

这就是我所做的。

    static void Main(string[] args)
    {
        DateTime startDate = new DateTime();
        DateTime endDate = new DateTime();

        List<FakeAppointments> appointmentsFromDatabase = new List<FakeAppointments>();

        var appointmentsBetweenStartDateAndEndDate = appointmentsFromDatabase.Where(p => p.SnapshotTime >= startDate && p.SnapshotTime <= endDate).ToList();
        int sum = appointmentsBetweenStartDateAndEndDate.Sum(p => p.AvailableSlots);

        Console.ReadKey();
    }

    public class FakeAppointments
    {
        public DateTime SnapshotTime;
        public int AvailableSlots;
    }

【讨论】:

    猜你喜欢
    • 2023-03-20
    • 2013-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-06
    • 2014-03-05
    • 1970-01-01
    • 2016-09-11
    相关资源
    最近更新 更多