从事务日志中计算机架中的活动框

Count active boxes in the rack from transaction logs

我这里有2张桌子

  1. 机架
Id RackName
1 Rack A
2 Rack B
  1. 机架交易
Id RackId Barcode Event DateTime
1 1 ABC1234 IN 2021-07-12
2 1 ABC1234 OUT 2021-07-20
3 1 ABC1235 IN 2021-07-21
4 1 ABC1236 IN 2021-07-21
5 1 ABC1236 OUT 2021-07-23
6 1 ABC1237 IN 2021-07-21
7 1 ABC1238 IN 2021-07-21
8 1 ABC1238 OUT 2021-07-23

条形码 ABC1235ABC1237 尚未签出。所以 RACK A 内的总计数框是 2.

那么根据给定的示例数据,我如何使用 linq 生成?

var getTotal = await _context.RackBoxLogs.Where(c => c.RackId == rackId)
                                .GroupBy(c => new { c.Barcode,c.Event })
                                .Select(g => new { g.Key, MaxDate = g.Max(c => c.CreatedOn),Event = g.Key.Event })
                                .Where(c=> c.Event == "IN")
                                .CountAsync(); 

即使我已经按条形码分组并过滤了最大日期,我仍然得到错误的结果。有什么想法吗?

我认为这应该适用于 EF 5。不幸的是 EF 5 不能(还)翻译 GroupBy().Select(g => g.Last()).

var getTotal = RackTransaction
                .Where(rt => rt.RackId == rackId)
                .Select(rt => rt.Barcode)
                .Distinct()
                .Select(b => RackTransaction.Where(rt => rt.Barcode == b).OrderBy(rt => rt.DateTime).Last())
                .Where(rt => rt.Event == "IN")
                .Count();

此查询应获得所需的计数:

var getTotal = await _context.RackBoxLogs
    .Where(c => c.RackId == rackId)
    .GroupBy(c => new { c.Barcode })
    .Where(g => g.Sum(x => x.Event == "IN"  ? 1 : 0) > 
                g.Sum(x => x.Event == "OUT" ? 1 : 0)
    )
    .CountAsync();