How to generate a statement per month in the database?

2

I have to generate an extract in the database that is similar to the bank statement and present the cumulative balance.

I have the following columns

Data, Debito, Crédito. 

Data entry is daily but the statement I need is per month.

01/01/2015 – Credito 100
02/01/2015 – Débido 30
02/01/2015 – credito 70
01/02/2015 – debito 50
01/02/2015 – credito 80
02/02/2015 – debito 20
01/03/2015 – credito 60
01/03/2015 – debito 20

data        debito  credito saldo
01/01/2015          100     100
02/01/2015  30              70
02/01/2015          70      140
01/02/2015  50              90
01/02/2015          80      170
01/02/2015  20              150
01/03/2015          60      210
01/03/2015  20              190

The result should be:

data    debito  credito saldo
jan     30      170     140
fev     70      80      150
mar     20      60      190
    
asked by anonymous 06.09.2015 / 00:58

2 answers

2

To do the balance it would look like this:

SELECT DATE_FORMAT(data,'%d/%m/%Y') AS data,
    IF(tipo = 'D', valor, '') AS debito,
    IF(tipo = 'C', valor, '') AS credito,
    (SELECT SUM(IF(tipo = 'C', valor, -valor))
        FROM Lancamento L2
        WHERE L2.id <= Lancamento.id) AS saldo
FROM Lancamento

See running SQLFidle .

This form is not very efficient but solves it. On a production system I would think of something better.

To group by month would do:

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 Lancamento AS L2
         WHERE DATE_FORMAT(Lancamento.data,'%Y%m') >= DATE_FORMAT(L2.data,'%Y%m')
    ) AS saldo
FROM Lancamento
GROUP BY MONTH(data), YEAR(data)

See running SQLFiddle .

I do not really trust this solution but it seems to solve what was asked.

I would particularly adopt a solution by taking these releases and mounting the extract in PHP. I'm not saying that I should do this but in my specific case I get better with imperative than declarative languages. I would do it faster, thinking too little, I would trust the result more, it would be more efficient and easier to maintain. Probably better to leave the SQL code but I will not spend more time on it.

I would probably have a different structure which would make it easier to query.

    
06.09.2015 / 05:50
1

I got the result waiting, my table is not in normal forms, but it would be very costly to have to reprogram.

follows the expected result link.

SQL Fiddle

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 
    
08.09.2015 / 03:51