Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在mysql中聚合和计算值_Mysql_Sql - Fatal编程技术网

在mysql中聚合和计算值

在mysql中聚合和计算值,mysql,sql,Mysql,Sql,我有一个包含一些传入和传出数据的表 +====+===========+==========+============+ | id | flow(int) | quantity | product_id | +====+===========+==========+============+ | 1 | 0 | 100 | 1 | +----+-----------+----------+------------+ | 2 | 1

我有一个包含一些传入和传出数据的表

+====+===========+==========+============+
| id | flow(int) | quantity | product_id |
+====+===========+==========+============+
| 1  | 0         | 100      | 1          |
+----+-----------+----------+------------+
| 2  | 1         | 20       | 1          |
+----+-----------+----------+------------+
| 3  | 1         | 30       | 1          |
+----+-----------+----------+------------+
| 4  | 0         | 10       | 1          |
+----+-----------+----------+------------+
| 5  | 1         | 30       | 2          |
+----+-----------+----------+------------+
| 6  | 2         | 10       | 2          |
+----+-----------+----------+------------+
| 7  | 0         | 10       | 2          |
+====+===========+==========+============+
列流是一种枚举类型,0-传入,1和2-传出操作

如何获得特定产品的当前余额

产品1的余额应为60=收入100-支出20-支出30+收入10

产品2应具有-30余额=支出30-支出10-收入10


单次查询是否可以以任何有效的方式进行?

这将是条件聚合:

select product_id,
       sum(case when flow like 'out_%' then - quantity else quantity end) as net_quantity
from t
group by product_id;

这将是条件聚合:

select product_id,
       sum(case when flow like 'out_%' then - quantity else quantity end) as net_quantity
from t
group by product_id;
使用以下命令:

SELECT product_id,
       SUM( IF(flow IN ('1','2'), 
               -1*quantity, 
               quantity) ) AS balance
FROM table_name
GROUP BY product_id;
使用以下命令:

SELECT product_id,
       SUM( IF(flow IN ('1','2'), 
               -1*quantity, 
               quantity) ) AS balance
FROM table_name
GROUP BY product_id;

添加更多示例表数据,例如另一个产品。还指定预期结果集。添加更多示例表数据,例如另一个产品。还要指定预期的结果集。它是否比sum..if更有效?他没有指定他的sgbd。它是否比sum更有效..if?他没有指定他的sgbd。选择product_id,sum IFflow=0,quantity,-1*quantity作为表_name GROUP BY product_id的余额;如果是假的,或者如果!真理只是相同的东西。因此,如果条件可以改变,保持逻辑相同,则按产品id从表名称组中选择产品id,总和IFflow=0,数量,-1*数量作为余额;如果是假的,或者如果!真理只是相同的东西。所以,如果条件可以改变,保持逻辑相同