I have a query that gets quantity 1, value 1 , total 1 what I am trying to get is the following result
quantity 1, value 1, total 1, sum quantity, sum total / sum quantity as value summ, sum total
80 - 3.8 - 304 , 80 - 3.8 - 304
40 - 3.75 - 150, 120 - 3.783 - 454
40 - 3.8 - 152, 160 - 37875 - 606
that is to say, to be able to obtain the sum of the total, (total 1 + previous total sum)
to then do the division with quantity 1
I have tried using
SELECT
@prev:= @prev + total 1 as column1, @prev / quantity 1 as value
from table;
but I don’t get the expected results
use MySQL 5.6 and windows S.O
3
Answers
you can use user-defined variables to achieve the desired result. Here’s an example query that calculates the cumulative sum and division:
Make sure to replace table_name with the actual name of your table.
This query initializes the
@prev
variable to0
. Then, it selects the columns quantity, value, and total, and performs calculations using the user-defined variable@prev
to calculate the cumulative total and the division. The results are displayed in the columns: quantity, value, total, cumulative_total, value_summ, and sum_total.Note that user-defined variables are session-specific, so the @prev variable will retain its value within the same session. If you run this query multiple times in the same session, make sure to reset the variable by executing SET @prev := 0; again before running the query.
Without using an
order by
clause, the results of your@prev
value would be indeterministic. You need to have a column (id, timestamp…) that uniquely identifies the order of your rows, so the SQL can determine correctly what the previous value is.consider the following example based on your sample data:
demo
If you are using MySQL 5.6 and want your answer in one single query
This should work