Total month to month that disappear with previous months

4

I need a SELECT to bring the sum of data month by month and add up with the total of the previous months.

No SELECT below is bringing the sum month to month.

SELECT DISTINCT MONTH(data_pgto_bx) as mes, SUM(total_bx) FROM gc_baixas
WHERE sit_bx = 3 GROUP BY mes ORDER BY mes ASC
So far so good with SELECT above, my problem is a bit more complex, I need this SELECT to also add the total_bx column to the previous months. Example:

  • In month 10, bring the sum of the column total_bx from every month to the month 10;

  • In month 11 bring the sum of every month until month 11;

asked by anonymous 24.11.2014 / 14:00

1 answer

5

As @gmsantos has confirmed there are no analytic functions available in MySQL . The solution then passes by running a% of% within the% of% main that computes the results month to month:

SET @totalagregado := 0;
SELECT 
 resultados_mes.mes as mes,
 resultados_mes.soma_mes as soma_mes,
 (@totalagregado := @totalagregado + resultados_mes.soma_mes) as soma_agregada
FROM
(
  SELECT DISTINCT MONTH(data_pgto_bx) as mes, SUM(total_bx) as soma_mes
  FROM gc_baixas
  WHERE sit_bx = 3 
  GROUP BY mes
  ORDER BY mes ASC  
) as resultados_mes

Example in SQLFiddle .

The result of this query will have the following format:

  

Month | Total of the month | Total Added

     

1 | 1234 | 1234

     

2 | 1234 | 2468

     

...

    
24.11.2014 / 14:26