SQL查询结果问题
查询用于获取某个客户端的余额SQL查询结果问题,sql,sql-server,sql-server-2008,tsql,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
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
该问题与销售发票有关#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
我认为子查询中的逻辑有点不正确
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;
或者,如果借方
和贷方
可能具有空值
值:
sum(coalesce(debit, 0) - coalesce(credit, 0)) over (partition by custid order by date, invoiceid)
这3张唱片有什么特别之处?为什么它们求和而没有其他条件?您的问题是,在子查询中,您的条件之一是x.invoiceid=t.invoiceid,因此,不同的发票ID除了自身之外不能加任何值。因此,我可以做的是,但现在余额不包含收据凭证值。此代码中的任何内容都不会像原始查询中那样处理借项和贷项。这只是重新安排了子查询where子句中的布尔表达式。因此,您能否帮助我进行另一个查询,以获得我在问题中提到的输出,谢谢
sum(debit - credit) over (partition by custid order by date, invoiceid)
sum(coalesce(debit, 0) - coalesce(credit, 0)) over (partition by custid order by date, invoiceid)