简体   繁体   中英

SUM in just one table - Mysql

I have the following situation. I'm setting up a stock control system and through it, I control the in and out of products.

In a table I have the products (code, description).

In the other table, record the movement of the products (code, product_code, type [in, out], quantity, date).

When I try to make the calculation of what comes in, the less that comes out, it does not work.

MY QUERY:

SELECT SUM(s1.quantity) - SUM(s2.quantity)
FROM `stock_movement` AS s1
JOIN `stock_movement` AS s2 
ON s1.code_product = s2.code_product
WHERE s1.type = 'IN'
AND s2.type = 'OUT';

RESULTS: 80

The correct result here should be (40 + 20) - (10 + 10) = 40, but this query is considering that all inputs are of type IN and OUT, so the result 80.

Anyone have any idea what I'm doing wrong? The table data below are as follows:

TABLE STOCK_MOVEMENT:

| CODE | CODE_PRODUCT | TYPE | QUANTITY | DATA |
| 1 | 30 | IN | 20 | 2018-01-20 |
| 2 | 30 | IN | 40 | 2018-02-03 |
| 3 | 30 | OUT | 10 | 2018-01-20 |
| 4 | 30 | OUT | 10 | 2018-02-03 |

TABLE STOCK:

| CODE | DESCRIPTION |

| 30 | TEST_PRODUCT |

You don't need to self join here, just use conditional aggregation:

SELECT
    CODE_PRODUCT,
    SUM(CASE WHEN TYPE = 'IN'  THEN QUANTITY ELSE 0 END) -
    SUM(CASE WHEN TYPE = 'OUT' THEN QUANTITY ELSE 0 END) AS diff
FROM stock_movement
GROUP BY CODE_PRODUCT;

Note that I am aggregating by product. For your particular sample data set, there is only one product, so we could remove GROUP BY and get the same result. But in practice you might want a solution which handles multiple products.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM