【发布时间】:2021-02-14 11:59:41
【问题描述】:
我正在尝试使用以下 mysql 查询来获取到达产品的总购买、销售和 sotck:
select fk_product_id,
(select sum(quantity) from entry_products where status =0 ) as total_purchase,
(select sum(quantity) from entry_products where status =1)as total_sales,
(select sum(quantity) from entry_products where status =0 ) -
(select sum(quantity) from entry_products where status =1) as stock
from entry_products group by fk_product_id
输出
fk_product_id total_purchase total_sales stock
1 1700 660 1040
2 1700 660 1040
3 1700 660 1040
My Expected Output is
fk_product_id total_purchase total_sales stock
1 350 200 150
2 1100 460 640
3 250 0 250
【问题讨论】:
-
很好地分享了您的查询,以及您获得的输出和预期的输出。您可能需要为我们提供最少的样本输入匹配输出来帮助您。您可以使用 sum(if(status = 0, 0, quantity)) 之类的条件来代替子查询。