Skip to content
Advertisement

Cumulative balance across two tables

I want to get data from 2 tables ordering them by date: to get the cumulative balance for the customer

The 2 tables that I want to get data from are my tables: transfers & trans_payments

transfers:

trans_payments:

Let’s assume I have this data:

transfers:

trans_payments:

I want to create a view to show customers action on Purchases and Payments like this:

Customer 5:

Last row is the final balance for the customer

I tried this:

But I have a problem that if 2 customers paid on the same date the payments will calculate for 2 customers that paid on the same date, I tried to add the ID for the 2 to prevent the query from grouping data But I’m still facing mistakes in the balance.

How can I do this in a proper way?

Advertisement

Answer

I think that’s union all and a window sum():

When there are rows in both tables for a given date, this puts the transfer(s) first.

Demo on DB Fiddle:

cust_id | final | value | date       | balance
------: | ----: | ----: | :--------- | ------:
      5 |  3000 |     0 | 2020-09-22 |    3000
      5 |     0 |  1000 | 2020-09-22 |    2000
      5 |     0 |  1500 | 2020-09-23 |     500
      5 |  1500 |     0 | 2020-09-25 |    2000
      5 |     0 |  1000 | 2020-10-01 |    1000
     10 |     0 |  2000 | 2020-01-01 |   -2000
     10 |  4000 |     0 | 2020-09-28 |    2000
     10 |     0 |  1000 | 2020-09-28 |    1000

You can use a where clause to filter on a given customer.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement