我一直都明白,该CASE
声明遵循“短路”原则,即如果先前步骤的评估结果为真,则不会对后续步骤进行评估。(这个答案Does SQL Server CASE statement evaluate all conditions or exit on first TRUE condition?是相关的,但似乎没有涵盖这种情况并且与 SQL Server 相关)。
在下面的示例中,我希望MAX(amount)
根据开始日期和支付日期之间的月份数来计算不同的月份范围。
(这显然是一个构造的示例,但逻辑在我看到问题的实际代码中具有有效的业务推理)。
如果开始日期和支付日期之间的时间小于 5 个月,则将使用表达式 1,否则将使用表达式 2。
这会导致错误“ORA-01428:参数‘-1’超出范围”,因为 1 条记录的数据条件无效,导致 ORDER BY 的 BETWEEN 子句的开头为负值。
查询 1
SELECT ref_no,
CASE WHEN MONTHS_BETWEEN(paid_date, start_date) < 5 THEN
-- Expression 1
MAX(amount)
OVER (PARTITION BY ref_no ORDER BY paid_date ASC
ROWS BETWEEN MONTHS_BETWEEN(paid_date, start_date) PRECEDING
AND CURRENT ROW)
ELSE
-- Expression 2
MAX(amount)
OVER (PARTITION BY ref_no ORDER BY paid_date ASC
ROWS BETWEEN 5 PRECEDING AND CURRENT ROW)
END
END
FROM payment
所以我进行了第二个查询,以首先消除可能发生这种情况的任何地方:
SELECT ref_no,
CASE WHEN MONTHS_BETWEEN(paid_date, start_date) < 0 THEN 0
ELSE
CASE WHEN MONTHS_BETWEEN(paid_date, start_date) < 5 THEN
MAX(amount)
OVER (PARTITION BY ref_no ORDER BY paid_date ASC
ROWS BETWEEN MONTHS_BETWEEN(paid_date, start_date) PRECEDING
AND CURRENT ROW)
ELSE
MAX(amount)
OVER (PARTITION BY ref_no ORDER BY paid_date ASC
ROWS BETWEEN 5 PRECEDING AND CURRENT ROW)
END
END
FROM payment
不幸的是,有一些意想不到的行为意味着表达式 1将使用的值得到验证,即使该语句不会被执行,因为否定条件现在被外部捕获CASE
。
我可以通过使用ABS
on the MONTHS_BETWEEN
in Expression 1来解决这个问题,但我觉得这应该是不必要的。
这种行为是否符合预期?如果是这样,“为什么”对我来说似乎不合逻辑,更像是一个错误?
这将创建一个表和测试数据。查询只是我检查是否采用了正确的路径CASE
。
CREATE TABLE payment
(ref_no NUMBER,
start_date DATE,
paid_date DATE,
amount NUMBER)
INSERT INTO payment
VALUES (1001,TO_DATE('01-11-2015','DD-MM-YYYY'),TO_DATE('01-01-2016','DD-MM-YYYY'),3000)
INSERT INTO payment
VALUES (1001,TO_DATE('01-11-2015','DD-MM-YYYY'),TO_DATE('12-12-2015','DD-MM-YYYY'),5000)
INSERT INTO payment
VALUES (1001,TO_DATE('10-03-2016','DD-MM-YYYY'),TO_DATE('10-02-2016','DD-MM-YYYY'),2000)
INSERT INTO payment
VALUES (1001,TO_DATE('01-11-2015','DD-MM-YYYY'),TO_DATE('03-03-2016','DD-MM-YYYY'),6000)
INSERT INTO payment
VALUES (1001,TO_DATE('01-11-2015','DD-MM-YYYY'),TO_DATE('28-11-2015','DD-MM-YYYY'),10000)
SELECT ref_no,
CASE WHEN MONTHS_BETWEEN(paid_date, start_date) < 0 THEN '<0'
ELSE
CASE WHEN MONTHS_BETWEEN(paid_date, start_date) < 5 THEN
'<5'
-- MAX(amount)
-- OVER (PARTITION BY ref_no ORDER BY paid_date ASC ROWS
-- BETWEEN MONTHS_BETWEEN(paid_date, start_date) PRECEDING
-- AND CURRENT ROW)
ELSE
'>=5'
-- MAX(amount)
-- OVER (PARTITION BY ref_no ORDER BY paid_date ASC ROWS
-- BETWEEN 5 PRECEDING AND CURRENT ROW)
END
END
FROM payment