我在解决 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);
手动计算每天剩余的公式 (现有 - 销售数量)+ 购买数量 = 剩余
最佳答案
我想简单检查一下sales.qty < purchase.qty
行不通的。因为即使你有 sales.qty < purchase.qty
但是如果有前一天的剩菜,那么你将首先使用这些剩菜。
你应该使用尝试这个:
with cte as(
select s.id,s.Sid,sDate,s.Productid,s.qty AS Qty,s.qty as saleqty,p.qty as productqty,p.price
,sum(p.qty-s.qty) over (order by sdate) as leftover
from purchase P
inner join sales S
on p.productid=s.productid
and p.pdate=s.sdate
)
select id, Sid,sDate,Productid,Qty,
case when lag(leftover) over (order by sdate)>0 then lag(leftover *price) over( order by sdate)
+( saleqty-lag(leftover) over (order by sdate)) * price
else saleqty * price end as profit
from cte;
关于sql查询fifo库存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57369341/