简体   繁体   中英

Sum two rows (one previous row and one is current row in same table) in SQL

I have this table:

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

Now I want to execute a query to add the deposited amounts and subtract the withdrawals from the previous days entry in_bank . How can I do that? Can any one help me on that? This is my query:

select date_on, in_bank,((in_bank+deposited)-withdrawal)
  from  tablename where date_on > '2012-09-01' order by date_on
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

The query will assume the balance was zero if no previous days date can be found.

Added a fiddle http://sqlfiddle.com/#!2/d8261/14

Try this:

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

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

I am not very familiar with mysql but this might help

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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