基于MVC ASP.net的LINQ查询中的每个记录运行总计

时间:2012-10-29 01:29:11

标签: c# .net sql linq

我遇到了两个问题:

我尝试将ROW_NUMBER分配给我的SQL视图,并根据行号执行运行总和(因此根据每条记录得到总和),但结果表现非常明显。

我知道如何在日期的T-SQL中执行此操作:

http://i50.tinypic.com/15rgs3c.gif

此SQL语句中的RunningTotal列正是我需要的(逐项总和)。

http://i49.tinypic.com/6j2j4x.gif

但执行需要很长时间。

更新2
以下是我创建第二个视图的方式。

CREATE VIEW [dbo].[vCI_UNIONALL_ROW] AS
SELECT ROW_NUMBER() OVER(ORDER BY EffChkDt DESC) AS [Row]
    ,*
FROM vCI_UNIONALL
GO

我的模特:

public class UnionAllModel
{
    public int? InvoiceNumber { get; set; }
    [DataType(DataType.Currency)]
    public Decimal? Amount { get; set; }
    [DataType(DataType.DateTime)]
    public DateTime? EffChkDt { get; set; }
    [omitted for clarity]
}

到目前为止,这是我的LINQ查询:

using (var db = new PLOGITENS01Entities())
{
    var rvUnionAll = (from u in db.vCI_UNIONALL
                      orderby u.EffChkDt ascending
                      select new UnionAllModel()
                      {
                          InvoiceNumber = u.InvoiceNumber,
                          Date = u.Date,
                          AccountNumber = u.AccountNumber,
                          ClientName = u.ClientName,
                          Amount = u.Amount,
                          InAmount = u.InAmount,
                          OutAmount = u.OutAmount,
                          ClientRiskAdjs = u.ClientRiskAdjs,
                          SpecificAdjs = u.SpecificAdjs,
                          EffChkDt = u.EffChkDt,
                          PayStatus = u.PayStatus,
                          Type = u.Type
                      })
                     .ToList();

    return View(new GridModel(rvUnionAll));
}

1 个答案:

答案 0 :(得分:0)

您可以尝试创建将值添加到局部变量的运行总和:

int runningSum = 0;
var rvUnionAll = (from u in db.vCI_UNIONALL.AsEnumerable()
                      orderby u.EffChkDt ascending
                      select new UnionAllModel()
                      {
                          InvoiceNumber = u.InvoiceNumber,
                          Date = u.Date,
                          AccountNumber = u.AccountNumber,
                          ClientName = u.ClientName,
                          Amount = u.Amount,
                          InAmount = u.InAmount,
                          OutAmount = u.OutAmount,
                          ClientRiskAdjs = u.ClientRiskAdjs,
                          SpecificAdjs = u.SpecificAdjs,
                          EffChkDt = u.EffChkDt,
                          PayStatus = u.PayStatus,
                          Type = u.Type,
                          RunningSum = runningSum += u.Amount
                      })
                     .ToList();