EF Core 按日期分组并计算以前日期的值

EF Core group by date and count value for previous dates

我有一个table喜欢

Date        Balance A   Balance B
---------------------------------
2022.03.01  100         200
2022.03.01  200         500
2022.03.02  300         600
2022.03.02  50          100
2022.03.03  150         300
2022.03.03  200         700
2022.03.04  450         500
2022.03.04  600         100

我需要按日期分组并获得该日期和之前日期的总余额。

我可以这样做:

var groupedData = from d in _myContext.Balances 
                  group d by d.Date into dg
                  select new 
                         { 
                             Date = dg.Key, 
                             TotalBalanceA = dg.Sum(t => t.BalanceA),
                             TotalBalanceB = dg.Sum(t => t.BalanceB),
                             PreviousTotalA = ?,
                             PreviousTotalB = ?
                         }

但我不确定如何获得以前日期的总数。

所以,如果我们采用上面的 table,我们应该得到像这样的分组数据:

Date        TotalBalanceA   TotalBalanceB   PreviousTotalA  PreviousTotalB
2022.03.01  300             700             0               0
2022.03.02  350             700             300             700
2022.03.03  350             1000            650             1400
2022.03.04  1050            700             1000            2400

更新:我想从数据库中获取这些数据。这是一个 IQueryable.

可以使用子查询吗?

var groupedData = from d in _myContext.Balances 
                    group d by d.Date into dg
                    select new 
                    { 
                        Date = dg.Key, 
                        TotalBalanceA = dg.Sum(t=>t.BalanceA),
                        TotalBalanceB = dg.Sum(t=>t.BalanceB),
                        PreviousTotalA = _myContext.Balances.Where(b => b.Date <= dg.Key).Sum(b => b.BalanceA),
                        PreviousTotalB = _myContext.Balances.Where(b => b.Date <= dg.Key).Sum(b => b.BalanceB)
                    }