从SQL Server表中选择开始和结束余额

时间:2015-04-12 21:25:45

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

我需要从具有这些表格的数据库中选择期初和期末余额

TransDate    Credit    Debit    Datasource
------------------------------------------
2014-01-01   5000      NULL     3
2014-01-07   NULL      2000     3
2014-01-11   5000      NULL     3
2014-02-03   5000      NULL     3
2014-02-06   NULL      5000     4
2014-02-11   5000      NULL     3
2014-02-21   NULL      5000     4
2014-02-28   5000      NULL     3
2014-03-01   5000      NULL     3

但它给了我这个,please see here

我做错了什么?

我预计也会看到

TransDate    Credit    Debit     Balance
------------------------------------------
2014-01-11   NULL      NULL      8000      <- opening balance     
2014-02-03   5000      NULL      
2014-02-06   NULL      5000      
2014-02-11   5000      NULL      
2014-02-21   NULL      5000      
2014-02-28   5000      NULL      13000     <- closing balance

我的查询是

Select 
    MAX(TransDate) TransDate, 0 Credit, 0 Debit, 
    SUM(ISNULL([Credit], 0) - ISNULL([Debit], 0)) AS Balance 
From 
    Transactions 
WHERE 
    DataSource = 4 OR DataSource = 3 
    AND TransDate < '2014/02/01'

UNION

Select 
    TransDate, Credit, Debit, 0 
From 
    Transactions 
WHERE 
    DataSource = 4 OR DataSource = 3 
    AND TransDate >= '2014/02/01' AND TransDate <= '2014/02/28'

UNION

Select 
    MIN(TransDate) TransDate, 0 Credit, 0 Debit, 
    SUM(ISNULL([Credit], 0) - ISNULL([Debit], 0)) AS Balance 
From 
    Transactions 
WHERE 
    DataSource = 4 OR DataSource = 3 
    AND TransDate >= '2014/02/01' AND TransDate <= '2014/02/28'

1 个答案:

答案 0 :(得分:2)

在SQL Server 2012+中,您将使用累积总和:

select sum(coalesce(credit, 0) - coalesce(debit, 0)) over (order by transdate) as balance
from table;

您可以使用各种方法获得第一笔和最后一笔余额,例如:

with b as (
      select t.* sum(coalesce(credit, 0) - coalesce(debit, 0)) over (order by transdate) as balance
      from table t
     )
select *
from ((select top 1 b.*
       from b
       order by transdate
      ) union all
      (select top 1 b.*
       from b
       order by transdate desc
      )
     ) b

您也可以在任何中间日期获得余额。