php - Mysql debit credit balance calculation -
i have following table little financial web app made php mysql. need calculation of debit , credit balance in mysql.
1.table: entries
+----+---------+------------+------------+ | id | type_id | narration | date | +----+---------+------------+------------+ | 1 | 3 | test input | 2015-01-05 | | 2 | 2 | test input | 2015-02-07 | | 3 | 2 | test input | 2015-04-02 | +----+---------+------------+------------+
2.table: entry_items
+----+----------+-----------+-------+--------+ | id | entry_id | ledger_id | type | amount | +----+----------+-----------+-------+--------+ | 1 | 1 | 1 | d | 2000 | | 3 | 1 | 2 | c | 2000 | | 4 | 2 | 2 | d | 550 | | 5 | 2 | 1 | c | 550 | +----+----------+-----------+-------+--------+
so able list amounts ledger id=1
select e.date date, i.type type, i.amount amount entries e left join entry_items on e.id=i.entry_id i.ledger_id = '1'
so result following
+------------+---+------+ | 2015-01-05 | d | 2000 | | 2015-02-07 | c | 550 | +------------+---+------+
so far not find way calculate balance.
the result want is:
+------------+------+---------+---------+ | date | type | amount | balance | +------------+------+---------+---------+ | 2015-01-05 | d | 2000 | 2000 | | 2015-02-07 | c | 550 | 1450 | +------------+------+---------+---------+
i'm totally lost current code:
select e.date date, i.type type, i.amount amount, sum(coalesce(case when type = 'd' amount end,0)) - sum(coalesce(case when type = 'c' amount end,0)) balance entries e left join entry_items on e.id=i.entry_id i.ledger_id = '1'
Comments
Post a Comment