Question

I am trying to get total debit, total credit and available balance for day from transactions table.

I have tried this so far...

        SELECT
        sum(credit),
        sum(debit),
                sum(credit) - sum(debit) as remaining_balance
                FROM transactions
    WHERE user_id = 2
group by created_at;

Its not giving correct results.

SQL FIDDLE....

http://sqlfiddle.com/#!2/25a27/2

I want to have results like bank/paypal statement, for example...

Date  - Debit - Credit - Balance
05/11 - 2.20  -        - 7.3
05/10 -       - 1.5    - 9.5
05/06 -       - 2.5    - 8
05/05 -       - 5.5    - 5.5

I am using laravel eloquent orm, so if its possible by ORM it would be great suggestion for me. thanks

Was it helpful?

Solution

You can solve it using a fairly simple JOIN;

SELECT DATE(a.created_at) date, a.debit, a.credit, 
  SUM(b.credit - b.debit) balance
FROM transactions a
LEFT JOIN transactions b
  ON DATE(a.created_at) >= DATE(b.created_at)
GROUP BY DATE(created_at)
ORDER BY DATE(created_at) DESC

An SQLfiddle to test with.

The problem here is that the JOIN condition and the GROUP BY condition use a value calculated on a field instead of using the field itself. This will limit the use of indexes and make the query really slow for large amounts of data.

A solution would be to add a separate DATE field which holds the date of the transaction. This will allow the JOIN/GROUP BY to work directly on a field and it can use indexing much more efficiently.

OTHER TIPS

Your GROUP BY is in the wrong place

Grouping by a day works like this:

SELECT 
  user_id,
  sum(credit),
  sum(debit),
  sum(credit) - sum(debit) as remaining_balance, 
  txn_description,
  DAY(created_at)
FROM transactions
WHERE user_id = 2
GROUP BY DAY(created_at);

More functions are available at the DateTime documentation

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top