简体   繁体   English

仅在一张表中求和-MySQL

[英]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). 在另一个表中,记录产品的移动(代码,product_code,[入,出]类型,数量,日期)。

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 结果: 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. 此处正确的结果应该是(40 + 20)-(10 + 10)= 40,但是此查询考虑的是所有输入的类型均为IN和OUT,因此结果为80。

Anyone have any idea what I'm doing wrong? 有人知道我在做什么错吗? The table data below are as follows: 下表数据如下:

TABLE STOCK_MOVEMENT: 表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 | CODE | DESCRIPTION | 描述|

| | 30 | 30 | TEST_PRODUCT | 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. 对于您的特定样本数据集,只有一种产品,因此我们可以删除GROUP BY并获得相同的结果。 But in practice you might want a solution which handles multiple products. 但实际上,您可能需要一个可处理多种产品的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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