首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用mysql保留每种产品的总购买量、销售额和库存

使用mysql保留每种产品的总购买量、销售额和库存
EN

Stack Overflow用户
提问于 2021-02-14 19:59:42
回答 1查看 62关注 0票数 1

我正在尝试使用mysql查询获取reach产品的总购买量、销售额和剩余sotck,如下所示:

代码语言:javascript
复制
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

输出

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-14 20:04:39

您需要条件聚合:

代码语言:javascript
复制
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 (对于true )或0 (对于false ),因此代码也可以这样编写:

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66195206

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档