Select 右边的最新 'N' 条记录 table 左边的每条记录 table 在 linq 上加入 sql

Select latest 'N' records on the right table for each record on left table of left join on linq to sql

我想 select 左边 table 右边的最新 2 条记录加入 linq 中左边 table 的每个 pers_Id。

select 前 1 或最新 1 有很多信息,但我想要根据订单日期从下面的表 2 中获取最新的 'n' 记录。

   Table1

pers_ID
10
20
null
40
meeting


    Table2

   pers_ID     STATUS            DATE
   10       initiated       10-APR-19
   10      processing       11-APR-19
   10      done             12-APR-19
   40      waiting          11-APR-19
   40      partial      12-APR-19
   40     interrupted       10-APR-19
   20      killed         11-APR-19


   result

pers_ID STATUS     date   
10  done        12-APR-19
10  processing  11-APR-19
40  partial     12-APR-19
40  waiting     11-APR-19
20  killed      11-APR-19

我遗漏了这里的重要部分。

  from t1 in table1
  join t2 in table2 on t1.pers_Id equals 
  t2.pers_Id into tb
  from t2 in tb.DefaultIfEmpty()
  // Logic to fetch the latest 2 records from table2.

如果可能,您应该尝试使用前 N 个项目而不是最后 N 个项目来构建查询。在这种情况下,当然可以通过倒序排序来代替。只需添加排序子句 (orderby) 并取前 N 项。由于您的日期似乎不准确,您可能需要按其他列进行排序。

var n = 5;
var query =
    (from t1 in table1
    join t2 in table2 on t1.pers_Id equals t2.pers_Id into t2s
    from t2 in t2s.DefaultIfEmpty()
    orderby t2.date descending, t2.pers_Id descending, t2.status descending
    select new { t1, t2 }).Take(n);

下面应该可以达到想要的效果。

 var n = 5;

 var query =  from t1 in table1
 join t2 in table2 on t1.pers_Id equals 
 t2.pers_Id into tb
 from t2 in tb.OrderByDescending(x=>x.ORD_CREATETIME).Take(n).DefaultIfEmpty()
 select new {t1,t2}

我认为对于这种情况,您必须使用 GroupBy,但查询会非常慢:

var n = 2;
var query = (from t1 in table1 join t2 in table2 on t1.pers_Id equals t2.pers_Id select new {PersId = t1.pers_ID, Status = t2.Status, Date = t2.Date})
    .GroupBy(g => g.PersId)
    .Select(x => x.OrderByDescending(o => o.Date)
        .Select(s => new {PersId = x.Key, Status = x.Status, Date = x.Date})
        .Take(n))
    .SelectMany(sm => sm);