繁体   English   中英

根据 SQL 中的销售和生产计算未来库存

[英]Calculate future inventory based an sales and production in SQL

我有 4 个表:存储、销售、生产、生产成本

存储示例

产品编号 数量
2022-03-27 1个 900
2022-03-27 2个 1200
2022-03-28 1个 950
2022-03-28 2个 1200

销售实例

日期 产品编号 数量
2022-04-2 1个 50
2022-04-15 1个 20

生产实例

日期 产品编号 数量
2022-04-1 1个 70
2022-04-20 1个 10

生产成本示例

产品编号 1个 2个 胶水
1个 0 1个 1个
2个 0 0 1个

生产成本描述了您是否需要生产某种产品以及需要多少产品。 在此示例中,您需要 1 个产品 2 和 1 个胶水来生产产品 1。

我想根据 SQL 的未来销售和生产来计算我未来的库存。我使用了一些 golang 代码,但如果 SQL 查询单独完成,我会更喜欢。

我尝试了不同的连接,但我无法弄清楚如何正确减去值并形成新行。

在这里,我们从存储中获取最新的库存数据,总结自此以来生产和销售的数量(忽略前面的行)并计算今天的库存数量。
我已将表 Production_cost 包含在连接中但未使用它。 是否应将所有乘积 2 转换为 1?

 create table Products( id int primary key); insert into Products values (1), (2);
 create table storage( Day date, ProductID int, Amount int, foreign key fk_storage_productID(ProductID) references Products(id)); insert into storage values ('2022-03-27', 1,900), ('2022-03-27', 2,1200), ('2022-03-28', 1,950), ('2022-03-28', 2,1200);
 create table Sales ( Day Date, ProductID int, Amount int, foreign key fk_sales_productID(ProductID) references Products(id)); insert into Sales values ('2022-04-02',1,50), ('2022-04-15',1,20);
 create table Production( Day Date, ProductID int, Amount int, foreign key fk_production_productID(ProductID) references Products(id)); insert into Production values ('2022-04-1', 1,70), ('2022-04-20', 1,10);
 create table Production_Cost( ProductID int, p1 int, p2 int, glue int, foreign key fk_production_cost_productID(ProductID) references Products(id)); insert into Production_Cost values (1, 0, 1, 1), (2, 0, 0, 1);
 select p.id as product, st.Amount as latest_count, coalesce(sum(sa.Amount),0) as sold, coalesce(sum(pr.Amount),0) as produced, st.Amount - coalesce(sum(sa.Amount),0) + coalesce(sum(pr.Amount),0) as calculated_stock from Products p left join ( select ProductID, Day, amount, rank() over (partition by ProductID order by Day desc) rn from storage )st on p.id = st.productID left join Sales sa on p.id = sa.productID left join Production pr on p.id = pr.productID left join Production_Cost pc on p.id = pc.productID where st.rn = 1 and (sa.Day > st.Day or sa.Day is null or st.Day is null) and (pr.Day > st.Day or pr.Day is null or st.Day is null) group by p.id, st.Amount
 产品 | 最新计数 | 已售出 | 生产 | 计算库存 ------: |  ----------: |  ---: |  ------: |  --------------: 1 |  950 |  140 |  160 |  970 2 |  1200 |  0 |  0 |  1200

db<> 在这里摆弄

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM