Query mysql add day value to previous days

Asked

Viewed 252 times

1

I have the following query:

SELECT * FROM  vw_total_diario WHERE pessoa ='Daniel' GROUP BY data;

It returns as follows:

2017-05-02 Daniel 6
2017-05-03 Daniel 2
2017-05-04 Daniel 8
2017-05-05 Daniel 1
2017-05-08 Daniel 10
2017-05-09 Daniel 2
2017-05-10 Daniel 8
2017-05-11 Daniel 6
2017-05-12 Daniel 5
2017-05-15 Daniel 4

I need her to return like this (current day + previous days):

2017-05-02 Daniel 6
2017-05-03 Daniel 8
2017-05-04 Daniel 16
2017-05-05 Daniel 17
2017-05-08 Daniel 27
2017-05-09 Daniel 29
2017-05-10 Daniel 37
2017-05-11 Daniel 43
2017-05-12 Daniel 48
2017-05-15 Daniel 52

How could you mount this query ?

1 answer

1


You can use a subquery to add up the quantity available in the previous days:

SELECT vtd.*,
       (SELECT SUM(vtd2.total)
          FROM vw_total_diario vtd2
         WHERE vtd2.pessoa = vtd.pessoa
           AND vtd2.data <= vtd.data
         GROUP BY vtd2.pessoa) as total_quantidade
  FROM  vw_total_diario vtd
 WHERE pessoa = 'Daniel'
 GROUP BY data;
  • It keeps returning the following: SQL Execution error #1242. Response from the database: Subquery Returns more than 1 Row

  • @otaciojb my fault, the GROUP BY was wrong

  • Pefeito, Thank you very much!

Browser other questions tagged

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