Skip to content
Advertisement

Grouped conditional sum in Oracle SQL

my_table shows the account balance of each person’s credits N months ago. From this table, I want to get the monthly sum of each person’s balances for the past 2 and 3 months and divide each sum by 2 and 3 respectively (that is, a moving average of the sum of balance for the last 2 and 3 months).

Please note that I need the sum of the balance in the past M months divided by M months.

One way to do this would be to:

and merge this result with

I want to know if this can be handled with a case or a conditional sum or something along these lines:

The desired result would look as follows:

Advertisement

Answer

If these two queries gives what you want and you need to merge them then only ma_2 needs conditional sum:

dbfiddle

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