SQL查询结果问题

时间:2016-01-12 14:59:59

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

该查询用于获取某个客户端的平衡

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 ='2' and date between '2015-01-01' and '2016-01-12'
order by InvoiceID, Type desc, Date

out out i get

InvoiceID   Type                Date    Debit   Credit  Balance
4          Sales Invoice    2015-06-09  520.00  0.00    520.00
4          Receipt Voucher  2016-01-04  0.00    520.00  0.00
6          Sales Invoice    2015-06-09  160.00  0.00    160.00
6          Receipt Voucher  2016-01-04  0.00    160.00  0.00
9          Sales Invoice    2015-06-09  850.00  0.00    850.00
9          Receipt Voucher  2016-01-04  0.00    850.00  0.00
13         Sales Invoice    2015-06-09  200.00  0.00    200.00
20         Sales Invoice    2015-07-11  1225.00 0.00    1225.00
176        Sales Invoice    2015-12-14  900.00  0.00    900.00

问题在于销售发票#13 20 176它应该对发票的借方进行汇总并显示余额

所以马上就应该像这样

   InvoiceID    Type                Date    Debit   Credit  Balance
    4          Sales Invoice    2015-06-09  520.00  0.00    520.00
    4          Receipt Voucher  2016-01-04  0.00    520.00  0.00
    6          Sales Invoice    2015-06-09  160.00  0.00    160.00
    6          Receipt Voucher  2016-01-04  0.00    160.00  0.00
    9          Sales Invoice    2015-06-09  850.00  0.00    850.00
    9          Receipt Voucher  2016-01-04  0.00    850.00  0.00
    13         Sales Invoice    2015-06-09  200.00  0.00    200.00
    20         Sales Invoice    2015-07-11  1225.00 0.00    1425.00
    176        Sales Invoice    2015-12-14  900.00  0.00    2325.00

1 个答案:

答案 0 :(得分:0)

我认为子查询中的逻辑略有偏差。

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.CustID = t.CustID AND
            (x.date < t.date or
             x.date = t.date AND x.InvoiceID <= t.InvoiceID
            ) 
     ) b
WHERE t.CustID ='2' and
      date between '2015-01-01' and '2016-01-12'
ORDER BY InvoiceID, Type desc, Date;

换句话说,累积金额的优先顺序应该是先日期,然后当日期相同时,使用发票。

这意味着您的所有值都被误算,因为每张发票都是重新开始的(使用您原来的逻辑)。但是,早期的发票已全额付款,因此您不会看到它们的问题。

注意:在更新版本的SQL Server中,使用累积和语法会更容易(也更有效):

sum(debit - credit) over (partition by custid order by date, invoiceid)

或者,如果debitcredit可以采用NULL值:

sum(coalesce(debit, 0) - coalesce(credit, 0)) over (partition by custid order by date, invoiceid)