sql查询运行余额

1 sql aggregate-functions sql-server-2008

我还是sql的新手,我需要你的帮助,我有一张看起来像这样的桌子

ses_date          trx_no        amount
02-04-2014       27487776I      1000
03-05-2014       27485776Y      -500
01-02-2014       65474645H      4500
09-01-2014       65474656D     -3400

我需要这样的输出

ses_date        trx_no        amount   Debit     Credit        Balance
02-04-2014       27487776I      1000     0.00      1000.00       1000
03-05-2014       27485776Y      -500    -500       0.00          500
01-02-2014       65474645H      4500    0.00       4500.00       5000
09-01-2014       65474656D     -3400    -3400.00   0.00          1600

就像一个帐户的声明,但在我自己的情况下,我没有单独借记和贷记,他们在一起.

非常感谢您的帮助和支持,您是最棒的.我的DBMS是microsoft SQL server 2008.我尝试使用此查询

SELECT ses_date, trx_no, amount, 
  CASE WHEN amount<0 THEN amount ELSE 0 END debit,
  CASE WHEN amount>0 THEN amount ELSE 0 END credit,
  (SELECT SUM(amount) FROM mytable a WHERE a.ses_date<=mytable.ses_date) balance
FROM mytable
ORDER BY ses_date;
Run Code Online (Sandbox Code Playgroud)

但它在余额栏中给出了(0.00)ZERO,但借方和贷方都可以.我该怎么办.

当我使用第二个查询

select ses_date, 
       trx_no, 
       amount, 
       case
           when amount < 0 then amount 
           else 0
       end as debit,
       case 
           when amount >= 0 then amount
           else 0 
       end as credit,
       sum(amount) over (order by ses_date) as balance
from the_table
order by ses_date
Run Code Online (Sandbox Code Playgroud)

错误是

消息102,级别15,状态1,行12''order'附近的语法不正确.

我该怎么办

a_h*_*ame 5

您没有指定DBMS,因此这是ANSI SQL

select ses_date, 
       trx_no, 
       amount, 
       case
           when amount < 0 then amount 
           else 0
       end as debit,
       case 
           when amount >= 0 then amount
           else 0 
       end as credit,
       sum(amount) over (order by ses_date) as balance
from the_table
order by ses_date
Run Code Online (Sandbox Code Playgroud)

SQLFiddle示例:http://sqlfiddle.com/#!15/c552e/1