首页 > 解决方案 > 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);

手工计算每天的剩余公式(现有-销售数量)+购买数量=剩余

标签: sqlsql-serverfifo

解决方案


希望这会有所帮助。

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

推荐阅读