使用sql计算余额

时间:2016-01-12 12:21:02

标签: sql sql-server sql-server-2008

我使用以下查询来获取某个客户的余额

SELECT  t.[InvoiceID], t.S_Type as Type,
        t.Date, t.Debit, t.Credit, b.Balance
FROM Statement as t CROSS apply
     (SELECT Balance = SUM(Debit) - SUM(Credit)
      FROM Statement as x
      WHERE (x.date < t.date or
             x.date = t.date 
            ) AND
            x.CustID = t.CustID
     ) b
WHERE t.CustID ='1' and date between '2015-01-01' and '2016-01-12'
order by InvoiceID, Type desc, Date

out put

InvoiceID   Type            Date       Debit    Credit  Balance
3         Sales Invoice     2015-06-09  200.00  0.00    225.00
3         Receipt Voucher   2016-01-04  0.00    200.00  0.00
5         Sales Invoice     2015-06-09  25.00   0.00    225.00
5         Receipt Voucher   2016-01-04  0.00    25.00   0.00

您可以看到余额值正确

应该是

InvoiceID   Type                  Date     Debit    Credit  Balance
    3         Sales Invoice     2015-06-09  200.00  0.00    200.00
    3         Receipt Voucher   2016-01-04  0.00    200.00  0.00
    5         Sales Invoice     2015-06-09  25.00   0.00    25.00
    5         Receipt Voucher   2016-01-04  0.00    25.00   0.00

更新

当我将x.CustID = t.CustID更改为x.InvoiceID = t.InvoiceID我尝试与另一个拥有所有销售发票的客户时,余额给出相同的借方值,而不是借记值的总和

out put

InvoiceID   Type               Date     Debit   Credit  Balance
1          Sales Invoice    2015-06-09  200.00  0.00    200.00
10         Sales Invoice    2015-06-09  850.00  0.00    850.00
12         Sales Invoice    2015-06-09  20.00   0.00    20.00
59         Sales Invoice    2015-09-03  0.00    0.00    0.00

2 个答案:

答案 0 :(得分:1)

您可以使用以下语句获得正确的结果:

SELECT  t.[InvoiceID], t.S_Type as Type,
        t.Date, t.Debit, t.Credit, b.Balance
FROM Statement as t CROSS apply
     (SELECT Balance = SUM(Debit) - SUM(Credit)
      FROM Statement as x
      WHERE (x.date < t.date or
             x.date = t.date 
            ) AND
            x.InvoiceID = t.InvoiceID 
            AND x.CustID = t.CustID
     ) b
WHERE t.CustID ='1' and date between '2015-01-01' and '2016-01-12'
order by InvoiceID, Type desc, Date

答案 1 :(得分:0)

结果对我来说是正确的。结果的第一行返回invoiceId = 3,余额列包含invoiceId=5的值,该值在同一天发生在同一客户端,因此应包括在内。如果您只想按发票计算值,请将x.CustID = t.CustID更改为x.InvoiceID = t.InvoiceID