sql - sql查询fifo库存
问题描述
我遇到了一个简单的 fifo sql 查询问题(计算每个销售日的利润)。
有两张表 Production 和 Invoice。对于每天的销售,我必须使用先进先出法输出总销售利润。
例如,对于第二天的利润,我必须使用前一天的剩余物品以及他们尊重的价格。
这是表格和所需的输出结果
CREATE TABLE Production
(
id int identity(1,1) primary key,
Productid varchar(10),
pdate date,
Qty int,
Price decimal(18, 2),
);
INSERT INTO Production (Productid,pDate, Qty ,Price) VALUES ('PD1', '01/01/2017', 8, 200);
INSERT INTO Production (Productid,pDate ,Qty ,Price) VALUES ('PD2', '02/01/2017', 14, 300);
INSERT INTO Production (Productid,pDate ,Qty ,Price) VALUES ('PD3', '03/01/2017', 15, 150);
CREATE TABLE Sales
(
id int identity(1,1) primary key,
Sid varchar(10),
sDate date,
Productid varchar(10),
Qty int,
);
INSERT INTO Sales (Sid,sDate ,Productid ,Qty) VALUES ('S001', '04/01/2017', 'PD1', 5);
INSERT INTO Sales (Sid,sDate ,Productid ,Qty) VALUES ('S002', '05/01/2019', 'PD2', 4);
INSERT INTO Sales (Sid,sDate ,Productid ,Qty) VALUES ('S003', '06/01/2019', 'PD3', 6);
手工计算每天的剩余公式(现有-销售数量)+购买数量=剩余
解决方案
希望这会有所帮助。
SELECT
s.sid,
s.sdate,
p.productid,
s.qty,
CASE
WHEN s.qty <= p.qty
THEN s.qty*p.price
ELSE p.qty*p.price + (s.qty-p.qty) * (SELECT price FROM purchase WHERE pdate IN (SELECT MAX(pdate) FROM purchase WHERE pdate < s.sdate))
END AS PROFIT
FROM purchase p
JOIN sales s
ON p.productid = s.productid
AND p.pdate = s.sdate
推荐阅读
- c# - ASP.NET 中的嵌套中继器控件
- swift - 如何指定将保存 SwiftUI 自定义视图的数组的类型信息
- angular - 如何使用 Angular 拦截器和管道来获取需要基本身份验证标头的图像的 http 获取请求
- elasticsearch - TFIDF 得分百分比
- python - 如何将字典列表与字典进行比较?
- c# - 使用 sql server 实现服务冗余
- python - 请帮我将 C++ 算法代码转换为 Python
- c# - 有没有办法在 asp.net json 文件的字符串中使用环境变量?
- jquery - 二维码图片下载后不显示
- node.js - 如何在 MongoDB 和 NodeJS 中聚合平均值