Search code examples
mysqlgroupingmultiplication

Mysql - Multiplicate two cols and subtract the difference


I have a DB structure in one table like this. Id, product_id, in_out, prod_size, prod_amount and a little example data:

1 | 2 | IN | 4 | 2
2 | 2 | UT | 4 | 1
3 | 3 | IN | 3 | 5

Now I want to multiplicate prod_size with prod_amount and get the difference between IN and UT posts grouped by the product_id. I have a beginning of something but it does not count right.

SELECT sk1.product_id 'product_id',
(sk2.prod_size*sk2.prod_amount)-(sk1.prod_size*sk1.prod_amount) as availability
FROM tbl sk1
LEFT JOIN tbl sk2 ON sk1.product_id=sk2.product_id
WHERE sk1.in_out='UT' AND sk2.in_out = 'IN'
GROUP BY sk1.product_id

So the expected result in this table should be:

2 | 4
3 | 15

Solution

  • You don't need to join with itself.

    select   product_id,
             sum((prod_size * prod_amount) * if(in_out = 'IN', 1, -1)) total
    from     tbl
    group by product_id
    
    product_id | total
    ---------: | ----:
             2 |     4
             3 |    15
    

    dbfiddle here