【问题标题】:Calculate a Running Total plus minus with merge column使用合并列计算运行总计加减
【发布时间】:2020-10-02 03:31:45
【问题描述】:

我有一个包含五列描述、期初余额、销售、销售退货、收据的表格。

我想合并期初余额,销售为“借方”和销售退货,接收为“贷方”。

如何将列名作为“余额”借方金额加和余额列中的贷方金额减去来计算运行总计?

我的尝试是

SELECT Description, (InvoiceAmount + OpeningBalance) as 'Dabit', (DrAmount + SaleReturn + BadDebtAmount) as 'credit', SUM (sale+ OpeningBalance-SaleReturn-recipt) over (ORDER BY id) AS RunningAgeTotal FROM tablename

【问题讨论】:

  • SELECT 描述,(InvoiceAmount + OpeningBalance)为“Dabit”,(DrAmount + SaleReturn + BadDebtAmount)为“credit”,SUM(sale+ OpeningBalance-SaleReturn-recipt)超过(ORDER BY id)为 RunningAgeTotal FROM 表名
  • edit 任何其他信息直接进入问题。

标签: c# sql sql-server linq


【解决方案1】:

您似乎在描述coalesce() 和一个窗口函数:

select description,
       coalesce(opening, sale) as debit,
       coalesce(return, receipt) as credit,
       sum(coalesce(opening, sale, 0) - coalesce(return, receipt,  0)) over (order by order by (case description when 'opening balance' then 1 when 'sale' then 2 when 'sale return' then 3 else 4 end))
from t
order by (case description when 'opening balance' then 1 when 'sale' then 2 when 'sale return' then 3 else 4 end);

【讨论】:

    【解决方案2】:

    以创建临时列表为代价,Linq 版本如下:

    假设你的原始来源是来自Sql数据库,那么你首先需要将数据带入内存,例如

    var records = OrderDetails
        .OrderBy(a=>a.Date)
        .Select(a => new 
        {
            a.Description,
            Debit = a.OpeningBalance + a.Sale,
            Credit = a.Return + a.SaleReturn
        }
        )
        .ToList();
    

    请注意,查询需要进行排序以确保以正确的顺序返回日期。您没有提到任何其他字段,所以我只是假设有一个名为 date 的字段可以使用。

    一旦内存中有数据,就可以添加 Balance 列,即

    decimal balance = 0;
    var list = records.Select(a => new
    {
        a.Description,
        a.Debit,
        a.Credit,
        Balance =  balance +=  (a.Debit - a.Credit),
    }).ToList();
    

    因为您正在引入一个局部变量并在 Linq 语句之外对其进行初始化,所以重要的是查询不会被枚举两次,除非余额已重置为零。您可以通过使用.ToList();.ToArray(); 来避免这种情况

    【讨论】:

    • 无法理解
    • 哪一部分不明白?
    • 小数余额 = 0; var list = _context.InvoiceTransation.Select(a => new { a.Description, a.Dr, a.Cr, Balance = balance += (a.Dr - a.Cr), }).ToList();错误是表达式树在这一行可能不包含赋值运算符 Balance = balance += (a.Dr - a.Cr)
    • 这仅适用于内存对象(Linq To Entities)。我知道您的原始数据来自 SQL,但我假设您的第二阶段(合并借方/贷方中的列)会将结果带入内存。我会更新答案以反映这一点。
    猜你喜欢
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-04
    • 1970-01-01
    相关资源
    最近更新 更多