我正在尝试重构一个在DB2 / iSeries上运行的MySQL查询,并且出现错误消息:使用标记的持续时间无效。
查看文档,我觉得下面的用法应该可以使用。
我想念什么吗?
SELECT
IFNULL(SUM(CASE WHEN CURDATE() BETWEEN n.start_date AND n.expire_date
THEN 1 ELSE 0 END), 0) AS current,
IFNULL(SUM(CASE WHEN CURDATE() - 365 DAY BETWEEN n.start_date AND n.expire_date
THEN 1 ELSE 0 END), 0) AS prior,
IFNULL(SUM(CASE WHEN '2018-12-31' - 7 DAY BETWEEN n.start_date AND n.expire_date
THEN 1 ELSE 0 END), 0) AS full
FROM salesnumbers;
答案 0 :(得分:1)
问题可能出在您的日期间隔上。尝试使用CURRENT DATE
代替CURDATE()
。另外,您可以直接在DB2中列出日期间隔+/-一定数量。
SELECT
COUNT(CASE WHEN CURRENT DATE BETWEEN n.start_date AND n.expire_date
THEN 1 END) AS current,
COUNT(CASE WHEN CURRENT DATE - 1 YEAR BETWEEN n.start_date AND n.expire_date
THEN 1 END) AS prior,
COUNT(CASE WHEN DATE('2018-12-31') - 7 DAY BETWEEN n.start_date AND n.expire_date
THEN 1 END) AS full
FROM salesnumbers;
请注意,我用条件计数替换了您的条件和。这使代码更加简洁,因为我们不必拼出明确的ELSE
条件(默认为NULL
)。