在SQL中求和两行(前一行,一行是同一表中的当前行)

时间:2012-11-20 11:27:36

标签: mysql sql

我有这张桌子:

Date_on      deposited  withdrawal   in_bank
2012-09-1      3000       2000        50000
2012-09-2/t    4000/t        0        54000
2013-09-3/t    3000       2000        55000

现在,我想执行查询以添加存款金额,并从前几天条目in_bank中减去提款。我怎样才能做到这一点?任何人都可以帮助我吗?这是我的问题:

select date_on, in_bank,((in_bank+deposited)-withdrawal)
  from  tablename where date_on > '2012-09-01' order by date_on

4 个答案:

答案 0 :(得分:1)

SELECT today.withdrawal, today.deposited, today.date_on,
  (IFNULL(today.deposited, 0) - IFNULL(today.withdrawal, 0)) + IFNULL((SELECT in_bank FROM tablename AS yesterday WHERE yesterday.date_on = DATE_SUB(today.date_on, INTERVAL 1 DAY)), 0)
FROM tablename AS today
WHERE date_on BETWEEN '2012-09-01' AND '2012-09-02'
ORDER BY date_on ASC

如果找不到前一天的日期,查询将假设余额为零。

添加了一个小提琴 http://sqlfiddle.com/#!2/d8261/14

答案 1 :(得分:0)

试试这个:

SELECT
  t1.date_on,
  t1.in_bank,
  (
    SELECT in_bank
    FROM
    (
      SELECT *, (@rownum2 := @rownum2 +1) rank
      FROM Table1,(SELECT @rownum2 :=0 ) t
      ORDER BY date_on 
     ) t2 WHERE t1.rank - t2.rank = 1
   ) - t1.withdrawal - deposited "total"
FROM
(
  SELECT *, (@rownum := @rownum +1) rank
  FROM Table1,(SELECT @rownum :=0 ) t
  ORDER BY date_on 
) t1;

SQL Fiddle Demo

答案 2 :(得分:0)

SELECT 
  date_on, 
  in_bank, 
  (( ISNULL(in_bank, 0) + ISNULL(in_deposited,0)) - ISNULL(withdrawal,0))
FROM tablename 
WHERE date_on > '2012-09-01' 
ORDER BY date_on

答案 3 :(得分:0)

我对mysql不是很熟悉,但这可能会有所帮助

select account.*,D.expectable from account left join 
(
select deposited - withdrawal + in_bank as expectable,DATE_ADD(Date_on,INTERVAL 1 DAY) as nDate from account
)
D on account.Date_on = D.nDate