SQL : ADD & MINUS based on Field type with GROUP BY condition
<p>This question is upgrade version <a href="https://stackoverflow.com/questions/37806168/sql-add-minus-based-on-field-type/">here</a>. The solution provided by Mr Giorgos Betsos are working fine. However i upgraded my requirement to be filter by PRODUCT_ID (using group by i assume). New table now look like this</p>

<pre><code>ID   |   BALANCE   |   ACTION_QTY   |   ACTION_TYPE |   PRODUCT_ID   |
---------------------------------------------------------------------|
1    |     0       |       3        |       ADD     |       12       |
2    |     0       |       2        |       DEDUCT  |       12       |  
3    |     0       |       6        |       ADD     |       11       |      
4    |     0       |       3        |       ADD     |       11       | 
5    |     0       |       1        |       DEDUCT  |       12       | 
6    |     0       |       7        |       ADD     |       15       | 
7    |     0       |       1        |       DEDUCT  |       15       | 
8    |     0       |       3        |       ADD     |       15       | 
9    |     0       |       7        |       DEDUCT  |       11       |  
10   |     0       |       9        |       ADD     |       12       |
</code></pre>

<p><a href="http://sqlfiddle.com/#!9/2ceae6/2" rel="nofollow noreferrer">SQL FIDDLE</a></p>

<p>How do i do the add/minus to <strong>BALANCE</strong> field based on <strong>PRODUCT_ID</strong> and order by <strong>ID</strong>? @Giorgos Betsos's SQL:</p>

<pre><code>SELECT ID, 
       @s := IF(ACTION_TYPE='ADD', @s + ACTION_QTY, @s - ACTION_QTY) AS BALANCE,
       ACTION_QTY,
       ACTION_TYPE
FROM tableA
CROSS JOIN (SELECT @s := 0) AS var
ORDER BY ID 
</code></pre>

<p>i tried to add GROUP BY PRODUCT_ID, but the result isnt correct.</p>

<p>Result that i want is like below:</p>

<pre><code>ID   |   BALANCE   |   ACTION_QTY   |   ACTION_TYPE |   PRODUCT_ID   |
---------------------------------------------------------------------|
1    |     3       |       3        |       ADD     |       12       |
2    |     1       |       2        |       DEDUCT  |       12       |  
3    |     6       |       6        |       ADD     |       11       |      
4    |     9       |       3        |       ADD     |       11       | 
5    |     0       |       1        |       DEDUCT  |       12       | 
6    |     7       |       7        |       ADD     |       15       | 
7    |     6       |       1        |       DEDUCT  |       15       | 
8    |     9       |       3        |       ADD     |       15       | 
9    |     2       |       7        |       DEDUCT  |       11       |  
10   |     9       |       9        |       ADD     |       12       | 
</code></pre>

<p>Please Help Me,
Many Thanks</p>