Mysql, Sum accumulated values by date and ID

Asked

Viewed 52 times

2

Good afternoon, I’m having a problem to get a relatively common result, I’ve seen some materials talking about but none applied to my specific need.

I need the cumulative total of each release, adding up all the previous ones, taking into account not only the launch sequence but also the release date. Note in the following examples that the last release should be the first to be calculated.

Information I have


Id| Descricao          | Valor   | Data      
1 | PAGAMENTO ENERGIA  |- 100.00 | 2021-01-11
2 | VENDAS DO DIA      |1500.00  | 2021-01-11
3 | SALDO INICIAL      |1000.00  | 2021-01-10

Result I get with the command:

SELECT cm.id, 
       cm.descricao, 
       cm.valor, 
       cm.datapagamento, 
       Sum(CASE 
             WHEN cm2.tipo = 1 THEN ( cm2.valor * -1 ) 
             ELSE cm2.valor 
           END) AS Total 
FROM   conta_movimentacao AS cm 
       INNER JOIN conta_movimentacao AS cm2 
               ON cm.id >= cm2.id 
GROUP  BY cm.id;

Id| Descricao          | Valor   | Data       | Total
1 | PAGAMENTO ENERGIA  |-100.00  | 2021-01-11 | -100.00
2 | VENDAS DO DIA      |1500.00  | 2021-01-11 | 1400.00
3 | SALDO INICIAL      |1000.00  | 2021-01-10 | 2400.00

What I really need:


Id| Descricao          | Valor   | Data       | Total
3 | SALDO INICIAL      |1000.00  | 2021-01-10 | 1000.00
1 | PAGAMENTO ENERGIA  |-100.00  | 2021-01-11 |  900.00
2 | VENDAS DO DIA      |1500.00  | 2021-01-11 | 2400.00

Someone could help me?

  • A ORDER BY cm.DataPagamento does not answer?

  • Worse than no friend, I have tried several ways. (I put the 3 tables organized in the question but for some reason it was not...)

  • 1

    "Running Total" with window functions https://popsql.com/learn-sql/mysql/how-to-calculatumulative-sum-running-total-in-mysql

  • It is an accounting system, this modeling is not appropriate. You would at least have to have one table identifying the accounts and another with the entries using the double start method so then follow the cash flow and assemble periodic balances.

  • @Motta I managed to settle with your friend tip! , Thank you.

1 answer

2

Thanks to @Motta’s comment I was able to resolve the issue.

User function: "sum(cm.Value) OVER (order BY cm.Datapayment Rows between UNBOUNDED PRECEDING and Current Row) as Balance" and got the return you expected.

Thank you for the force!

  • I just found out that the "OVER" function does not work in Mysql <= 5.7. Does anyone have any other idea?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.