我正在尝试根据前一行的新数量以及当前行的收据减去当前行的数量来计算新的数量。然后为下一行重复该过程。我希望基于item_no和loc重置。
以下是创建表格的代码。
CREATE TABLE [dbo].[zItemLocDailyAvgCost]
(
[ID] [numeric] (9,0) IDENTITY(1,1) NOT NULL,
[item_no] [nchar](30) NOT NULL,
[loc] [nchar] (3) NOT NULL,
[trx_dt] [datetime] NOT NULL,
[qty_lock] [int] NULL,
[orig_qty_on_hand] [decimal](13, 4) NULL,
[qty_received] [decimal](13, 4) NULL,
[unit_cost_received] [decimal] (16, 6) NULL,
[qty_issued] [decimal](13, 4) NULL,
[new_qty_on_hand] [decimal](13, 4) NULL,
[avg_cost] [decimal](16, 6) NULL
) [ON PRIMARY]
我还在item_no,loc和trx_dt上有一个主要索引,日期是降序。
CREATE UNIQUE CLUSTERED INDEX [zItemLocDailyAvgCost0]
ON [dbo].[zItemLocDailyAvgCost] ([item_no] ASC, [loc] ASC, [trx_dt] DESC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF,
DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
ON [PRIMARY]
GO`
我已经使用new_qty_on_hand值为“今天”填充了表格,然后想要根据今天的现有加上昨天的收据减去昨天发布的数据来计算昨天的数据。然后将值存储在昨天的new_qty_on_hand列中并重复该过程。我还想在item_no和loc组合更改时重置此过程。
我尝试了下面的CTE,它可以用于第一个记录,但之后会出现不正确的值。
WITH CTE AS (
SELECT
rownum = ROW_NUMBER() OVER (ORDER BY z.item_no asc, z.loc asc, z.trx_dt desc),
z.item_no
, z.loc
, z.trx_dt
, z.qty_lock
, z.orig_qty_on_hand
, z.new_qty_on_hand
, z.qty_issued
, z.qty_received
FROM zItemLocDailyAvgCost z
)
UPDATE CTE
SET new_qty_on_hand = case when CTE.qty_lock = 0 then prev.new_qty_on_hand + CTE.qty_received - CTE.qty_issued
else CTE.new_qty_on_hand end
, orig_qty_on_hand = prev.new_qty_on_hand
FROM CTE
LEFT JOIN CTE prev ON prev.rownum = CTE.rownum - 1
GO`
以下是上面代码的输出结果。
ID item_no loc trx_dt qty_lock orig_qty_on_hand qty_received unit_cost_received qty_issued new_qty_on_hand avg_cost
636 200001 XYZ 2016-05-28 1 NULL 0.0000 0.000000 75183.0004 552939.1530 0.110000
635 200001 XYZ 2016-05-27 0 552939.1530 635262.0000 0.110000 210379.8339 977821.3191 0.000000
634 200001 XYZ 2016-05-26 0 0.0000 176400.0000 0.110000 143545.8339 32854.1661 0.000000
633 200001 XYZ 2016-05-25 0 0.0000 235200.0000 0.110000 253137.0006 -17937.0006 0.000000
填充值后,我将单独更新“今天”,这实际上是一次性过程。
谢谢,
凯文