sql查询运行余额

时间:2014-04-17 16:41:52

标签: sql sql-server-2008 aggregate-functions

我仍然是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;

但它在余额栏中给出了(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

错误是

Msg 102,Level 15,State 1,Line 12'order'附近的语法不正确。

我将做什么

2 个答案:

答案 0 :(得分: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

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

答案 1 :(得分:0)

只是为了完整性,因为MySQL不是很...... ANSI,这是一个按ses_date排序的MySQL版本;

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;

An SQLfiddle to test with