1

I'm trying to create a query whereby I SUM a column but, if a column contains a certain value, the SUM value has to be reset at that point to take on this value.

ie:

SUM(i.units * op.add_or_subtract)   // This would translate to: '50 * -1' or '50 * 1'

The idea is that if op.op_code = 9, the SUM value should be reset to the current value of i.units as a manual adjustment has taken place.

op_code | units | add_or_subtract | SUM value |
--------|-------|-----------------|------------
   1    |   50  |       1         |     50
   1    |   50  |       1         |    100
   4    |   30  |      -1         |     70
   9    |  225  |       0         |    225

etc etc.

Can anyone help with how I could (if I can) achieve this in MySQL?

4

2 に答える 2

1

試す

select *, case when op_code = 9
               then @s := units
               else (@s := @s + (units * add_or_subtract)) 
          end as sum
from your_table, (select @s := 0) st
于 2012-08-07T09:16:30.497 に答える
0

これを試して:

SELECT SUM(IF(op_code = 9, (@var_sum := units), 
                           ((@var_sum := @var_sum + units) * add_or_subtract) 
          ) as sum_value
FROM table_name, (SELECT @var_sum := 0) a;
于 2012-08-07T09:15:42.483 に答える