你好,我正在尝试为某个客户提供声明
我使用的查询
SELECT distinct t.S_Type as Type,t.Number,t.Date, t.Debit, t.Credit, t.CustID, b.Balance
FROM Statement as t CROSS apply
(SELECT Balance = SUM(Debit) - SUM(Credit)
FROM Statement as x
WHERE x.Number<= t.Number AND x.CustID = t.CustID
) b
where t.CustID ='7003' and date between '8/21/2015' and '8/25/2015'
ORDER BY t.date
out put
type Number Date Debit CREDIT cust_id Balance
Sales Invoice 1 2015-08-23 400.00 0.00 7003 400.00
Sales Invoice 2 2015-08-23 1500.00 0.00 7003 1900.00
Receipt Voucher 3 2015-08-24 0.00 400.00 7003 1500.00
此处您注意到收据凭证编号值大于销售发票金额
当我的收据凭证编号值小于例如1的销售发票编号值时,会出现问题
当收据凭证低于销售价值时我得到的输出
type Number Date Debit CREDIT cust_id Balance
Sales Invoice 1 2015-08-23 400.00 0.00 7003 0.00
Sales Invoice 2 2015-08-23 1500.00 0.00 7003 1500.00
Receipt Voucher 1 2015-08-24 0.00 400.00 7003 -400.00
哪个不对,输出应该像第一个出来的问题
如果我将x.Number&lt; = t.Number更改为x.Number&gt; = t.Number,但是当我的Receipt Voucher值大于销售价值时,它会给出错误的值,但查询会给出正确的结果值也。
提前致谢
答案 0 :(得分:1)
不是在number
上进行计算,为什么不在date
和number
上进行计算?
SELECT t.S_Type as Type, t.Number, t.Date, t.Debit, t.Credit, t.CustID, 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.Number <= t.Number
) AND x.CustID = t.CustID
) b
WHERE t.CustID = '7003' and date between '2015-08-21' and '2015-08-25'
ORDER BY t.date;
或者,更好的是,只使用累积总和(在SQL 2012 +中):
SELECT t.S_Type as Type, t.Number, t.Date, t.Debit, t.Credit, t.CustID,
SUM(t.debit - t.credit) OVER (PARTITION BY t.CustId ORDER BY t.date, t.Number) as Balance
FROM Statement as t
WHERE t.CustID = '7003' and date between '2015-08-21' and '2015-08-25'
ORDER BY t.date;
答案 1 :(得分:0)
我认为第二种情况的问题是&#34;收据凭证&#34;是的,但日期更长。
您的查询似乎假设较低的&#34; Statement.Number&#34; show还有一个较低的声明。日期&#34;。
不应该是这种情况吗?
尝试更改第二个示例中的日期,以便&#34;收据凭证&#34;也有较早的约会。
或者,通过&#34; t.number&#34;来排序结果。而不是约会。