使用 11gR2,windows 7 客户端机器。我需要更新表missing_volume(如下),我需要在其中计算estimated_missing 列。本月的estimated_missing 列的计算需要上个月的数字(如下代码中所述)。我想要像第一个表一样的输出。请注意,记录从一月份开始,因此无法计算一月份的estimated_missing,但对于其余月份,只需更改“yr”和“mnth”即可完成(在代码中最后注释)。
yr mnth location volume actual_missing expected_missing estimated_missing
2013 January loc1 48037 24 57
2013 February loc1 47960 3660 53 24
2013 March loc1 55007 78 57 28
2013 April loc1 54345 72 58 77
编码:
UPDATE missing_volume g
SET
g.estimated_missing =
(
SELECT
CASE
-- If the previous month actual_missing number is less than 2 times than that of the previous month expected_missing number,
-- then for current month:
-- estimated_missing = previous_month(actual_missing/volume)*current_month(volume)
--
-- Else, for current month:
-- estimated_missing = previous_month(estimated_missing/volume)*current_month(volume)
WHEN (NVL(p.actual_missing, 0)/NVL(p.expected_missing, 1)) <= 2.0
THEN ROUND(NVL(p.actual_missing, 0)*( NVL(g.volume, 0)/NVL(p.volume, 1) ), 0)
ELSE
ROUND(NVL(p.estimated_missing, 0)*( NVL(g.volume, 0)/NVL(p.volume, 1) ), 0)
END
FROM
(
SELECT
yr,
mnth,
loc_cd,
volume,
actual_missing,
expected_missing,
estimated_missing
FROM missing_volume
WHERE yr = TRIM(TO_CHAR(ADD_MONTHS(SYSDATE, -2), 'YYYY')) -- For February it is -4, for March it is -3, for April it is -2
AND UPPER(mnth) = UPPER(TRIM(TO_CHAR(ADD_MONTHS(SYSDATE, -2), 'Month'))) -- For February it is -4, for March it is -3, for April it is -2
)p
WHERE g.yr = TRIM(TO_CHAR(ADD_MONTHS(SYSDATE, -1), 'YYYY')) -- For February it is -3, for March it is -2, for April it is -1
AND UPPER(g.mnth) = UPPER(TRIM(TO_CHAR(ADD_MONTHS(SYSDATE, -1), 'Month'))) -- For February it is -3, for March it is -2, for April it is -1
AND g.volume IS NOT NULL
AND TRIM(p.location) = TRIM(g.location)
);
当我为每个月运行代码时,代码确实为“estimated_missing”计算了正确的数字,但问题是在更新当前月份时,它也会删除上个月的记录。例如,如下所示,在我更新四月后,该列只有四月的记录,上个月的记录消失了,同样更新三月删除了二月等。我不明白为什么会这样!这是我得到的输出:
yr mnth location volume actual_missing expected_missing estimated_missing
2013 January loc1 48037 24 57
2013 February loc1 47960 3660 53
2013 March loc1 55007 78 57
2013 April loc1 54345 72 58 77
如果有人能解释为什么会发生这种情况(我的意思是代码中的缺陷在哪里)以及如何获得所需的输出(第一个表),将不胜感激。
谢谢