How to modify a daily statement for a monthly statement?

Asked

Viewed 493 times

0

I have a table that is not in the normal forms of database, but it has old data that I need to get.

I managed to get you to present me the daily statement, but now I need to modify to generate the monthly statement in the following query:

SELECT dia, mes, ano, credito, debito, format(saldo,2) as saldo
FROM (
    SELECT
        dia,
        mes,
        ano,
        credito,
        debito,
    @dc := dc AS tipo,
    @saldo := IF(@dc = 'C', @saldo + credito, @saldo - debito) AS saldo
    FROM lc_movimento, (SELECT @dc := 'C', @saldo := 0) as vars
    ORDER BY ano, mes, dia
) AS extrato 

This is the demo link:

Table in SQL Fiddle

This is the desired result.

    mês   ano     credito   debeito          saldo
    5     2014     2500     8722,6          -6222,6
    6     2014     0        12792,96        -19015,56
    7     2014     0        10884,82        -29900,38
    8     2014     0        10884,82        -40785,2
    9     2014     0        10022,68        -50807,88
    5     2015     650      7580,25         -57738,13

1 answer

2


I was able to get to the result but I had to create a VIEW. I used a @Maniero tip and it all worked out.

I smell a whirlwind, but it worked.

Follows the link demo SQL Fiddle.

SELECT DATE_FORMAT(data,'%d/%m/%Y') AS data,
    SUM(IF(tipo = 'D', valor, 0)) AS debito,
    SUM(IF(tipo = 'C', valor, 0)) AS credito,
    (SELECT SUM(IF(tipo = 'C', valor, -valor)) FROM vw_extrato AS L2
         WHERE DATE_FORMAT(vw_extrato.data,'%Y%m') >= DATE_FORMAT(L2.data,'%Y%m')
    ) AS saldo
FROM vw_extrato
GROUP BY MONTH(data), YEAR(data) ORDER BY data desc
  • To view is not necessary but even makes it easier to read the query. Accept your answer.

Browser other questions tagged

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