我正在使用MS SQL Server,并且具有下表'tmp_AVG_Weekly_Sales':
RowID SKU Shop Week Avg_Value LAMBDA PMF Value
1 ABC 200 2 1 2 0.13 NULL
2 DEF 250 2 2 4 0.018 NULL
3 XYZ 300 3 3 6 0.0024 NULL
我需要根据以下逻辑计算出Value字段-我正在使用游标和循环:
DECLARE @CUMULATIVE AS FLOAT = 0;
DECLARE @COUNT AS INT = 0;
DECLARE @LAMBDA AS FLOAT;
DECLARE @RowID AS INT;
DECLARE @PoissonCursor AS CURSOR;
DECLARE @THRESHOLD AS FLOAT = 0.99;
DECLARE @PMF AS FLOAT --= EXP(-@LAMBDA)
SET @PoissonCursor = CURSOR FOR
SELECT RowID
FROM
[tmp_AVG_Weekly_Sales]
OPEN @PoissonCursor;
FETCH NEXT FROM @PoissonCursor INTO @RowID;
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @LAMBDA = LAMBDA FROM [tmp_AVG_Weekly_Sales] WHERE RowID = @RowID
SELECT @PMF = PMF FROM [tmp_AVG_Weekly_Sales] WHERE RowID = @RowID
WHILE (@CUMULATIVE < @Threshold)
BEGIN
SET @CUMULATIVE += @PMF
SET @COUNT += 1
SET @PMF = @PMF * (@LAMBDA / @COUNT)
END
UPDATE [tmp_AVG_Weekly_Sales] SET [Value] = @COUNT - 1 WHERE RowID = @RowID
FETCH NEXT FROM @PoissonCursor INTO @RowID;
END
但是,以上只是用相同的值填充“值”字段:
RowID SKU Shop Week Avg_Value LAMBDA PMF Value
1 ABC 200 2 1 2 0.13 6
2 DEF 250 2 2 4 0.018 6
3 XYZ 300 3 3 6 0.0024 6
当我期望以下内容时:
RowID SKU Shop Week Avg_Value LAMBDA PMF Value
1 ABC 200 2 1 2 0.13 6
2 DEF 250 2 2 4 0.018 9
3 XYZ 300 3 3 6 0.0024 12
我要去哪里错了?
答案 0 :(得分:1)
您永远不会重置@CUMULATIVE
或增加@Threshold
,因此SET
调用的块仅在第一次执行时执行,而随后的每个UPDATE
仅使用那些原始值。