Ashishsingh
Ashishsingh

Reputation: 742

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

Upvotes: 0

Views: 1009

Answers (4)

almi_n
almi_n

Reputation: 51

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

Upvotes: 0

Rawkode
Rawkode

Reputation: 22592

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

Upvotes: 1

phoniq
phoniq

Reputation: 238

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

Upvotes: 0

Mahmoud Gamal
Mahmoud Gamal

Reputation: 79929

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

Upvotes: 0

Related Questions