我需要计算仓库的每日库存。
我有2张桌子
create table #Stock_Beginning
(
WH_CODE VARCHAR(4),
MNTH VARCHAR(6),
MODELCODE VARCHAR(5),
STOCKMONTH INT
)
INSERT INTO #Stock_Beginning
VALUES ('WH01', '201806', 'KD001', 10000)
create table #WH_TRANS
(
WH_CODE VARCHAR(4),
[DAY] DATETIME,
MODELCODE VARCHAR(5),
USEDQTY INT,
ORDERQTY INT
)
INSERT INTO #WH_TRANS
VALUES ('WH01', '2018-06-01', 'KD001', 1000, 0),
('WH01', '2018-06-02', 'KD001', 800, 1000),
('WH01', '2018-06-03', 'KD001', 700, 0),
('WH01', '2018-06-04', 'KD001', 1000, 2000),
('WH01', '2018-06-05', 'KD001', 1100, 500),
('WH01', '2018-06-06', 'KD001', 500, 0),
('WH01', '2018-06-07', 'KD001', 500, 800),
('WH01', '2018-06-08', 'KD001', 500, 0),
('WH01', '2018-06-09', 'KD001', 1000, 700),
('WH01', '2018-06-10', 'KD001', 800, 0);
我尝试了一些查询,但是没有得到正确的值。
WITH tmp_a AS
(
SELECT
WH_CODE,
CONVERT(DATETIME,concat(MNTH,'01')) MNTH,
MODELCODE, STOCKQTY
FROM
#Stock_Beginning
),
tmp_b AS
(
SELECT
a.WH_CODE, a.[DAY], a.MODELCODE,
ISNULL(b.STOCKQTY, 0) Beginning,
a.USEDQTY, a.ORDERQTY,
ROW_NUMBER() OVER(PARTITION BY a.WH_CODE ORDER BY a.[DAY]) SEQ
FROM
#WH_TRANS a
LEFT OUTER JOIN
tmp_a b ON a.WH_CODE = b.WH_CODE
AND a.MODELCODE = b.MODELCODE
AND a.[DAY] = b.MNTH
)
SELECT
WH_CODE, [DAY],
MODELCODE, BEGINNING,
USEDQTY, ORDERQTY,
CASE
WHEN SEQ = 1 THEN BEGINNING + ORDERQTY - USEDQTY
ELSE LAG (BEGINNING + ORDERQTY - USEDQTY, 1, BEGINNING + ORDERQTY - USEDQTY) OVER (ORDER BY [DAY]) + ORDERQTY-USEDQTY
END AS ENDING
FROM
tmp_b
结果看起来像这样:
我可以在查询中使用其他逻辑以获得所需结果吗?
请帮助
谢谢