【问题标题】:Total purchase, sales and stock remained for each product using mysql使用 mysql 为每个产品保留的总购买、销售和库存
【发布时间】: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)) 之类的条件来代替子查询。

标签: mysql sql join


【解决方案1】:

你需要条件聚合:

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 将布尔表达式计算为 1 对应 true0 对应 false,所以代码也可以这样写:

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

【讨论】:

  • 您可以使用公用表表达式来消除库存计算中的重复。
  • @AllanWind 我不认为这是必要的。一个体面的优化器不会再次重新计算相同的聚合列。此外,cte 只能在 8.0+ 版本中使用,并且使用子查询不会有任何改进。
  • @AllanWind 这甚至不是有效的 sql 语法。
  • 我在想更多的是不要重复自己(干)而不是速度。也不错。
  • @AllanWind 是的,这在语法上是正确的,但肯定会重新计算,因为它聚合了不同的表达式。至少通过使用之前计算过的相同表达式,我们可以希望它们会被重用而不是重新计算。
猜你喜欢
  • 1970-01-01
  • 2016-04-06
  • 2018-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多