简体   繁体   English

SQL Server查询减法

[英]SQL Server query sub subtraction

I have a Ledger table see the image 我有一个账本表,请参阅图片

I want to write a query which will subtract DR-CR data.. and requrn only due amount data. 我想编写一个查询,该查询将减去DR-CR数据..并仅查询到期金额数据。

its should omitted the paid amount 5000 because we have 2000 on 1-3-2014 and 3000 on 1-4-2014 它应该省略付款金额5000,因为我们在2014年1月3日有2000,在2014年4月4日有3000

can you please help... I have done this on application . 能否请您帮忙...我已在应用程序上完成此操作。 But I want to do this on my sql query. 但我想在我的SQL查询中执行此操作。 在此处输入图片说明

SQL Server 2008 doesn't have a cumulative sum. SQL Server 2008没有累积总和。 So, you have to use more complicated expressions. 因此,您必须使用更复杂的表达式。 The idea is to take the cumulative amount of DR, then subtract the sum of the credit, and choose the rows where the value is positive. 想法是取DR的累计金额,然后减去功劳总和,然后选择值为正的行。

select l.*
from (select l.*,
             (select sum(dr)
              from ledger l2
              where l2.id <= l.id
             ) as cumdr,
             sum(cr) over () as sumcr
      from ledger l
     ) l
where cumdr - sumcr > 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM