Skip to content
Advertisement

sql get balance at end of year

I have a transactions table for a single year with the amount indicating the debit transaction if the value is negative or credit transaction values are positive.

Now in a given month if the number of debit records is less than 3 or if the sum of debits for a month is less than 100 then I want to charge a fee of 5.

I want to build and sql query for this in postgre:

I am able get records per month level, I am stuck on how to proceed further and get the result.

Advertisement

Answer

You can start by generating the series of month with generate_series(). Then join that with an aggregate query on transactions, and finally implement the business logic in the outer query:

Demo on DB Fiddle:

| balance |
| ------: |
|    2746 |
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement