使用mysql的每个产品的总购买、销售和库存
我正在尝试使用mysql查询获取reach产品的总购买、销售和剩余库存,如下所示:使用mysql的每个产品的总购买、销售和库存,mysql,sql,join,Mysql,Sql,Join,我正在尝试使用mysql查询获取reach产品的总购买、销售和剩余库存,如下所示: 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_
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
您需要条件聚合:
select fk_product_id,
sum(case when status = 0 then quantity else 0 end) as total_purchase,
sum(case when status = 1 then quantity else 0 end) as total_sales,
sum(case when status = 0 then quantity else 0 end) - sum(case when status = 1 then quantity else 0 end) as stock
from entry_products
group by fk_product_id
由于MySql将布尔表达式计算为true
的1
或false的0
,因此代码也可以这样编写:
select fk_product_id,
sum((status = 0) * quantity) as total_purchase,
sum((status = 1) * quantity) as total_sales,
sum((status = 0) * quantity) - sum((status = 1) * quantity) as stock
from entry_products
group by fk_product_id
很好地共享了您的查询,以及您获得的输出和预期的输出。您可能需要为我们提供与输出匹配的最小样本输入,以帮助您。您可以使用sum(if(status=0,0,quantity))等条件来代替子查询。您可以使用公共表表达式来消除库存计算中的重复。@AllanWind我认为没有必要这样做。一个好的优化器不会再次重新计算相同的聚合列。此外,cte只能在8.0+版本中工作。使用子查询不会改善任何东西。@AllanWind这甚至不是有效的sql语法。我想的更多是不要重复你自己(干巴巴的)而不是速度。这也很好。@AllanWind yes这在语法上是正确的,但这肯定会被重新计算,因为它聚合了一个不同的表达式。至少通过使用以前计算过的相同表达式,我们可以希望它们将被重用,而不是重新计算。