我对 WHERE 子句中的 CASE 语句有疑问。在我的查询中,我想获取日期之前的行。日期在 3 列上进行检查。date1
is NOT NULL 所以我不需要有一个 NULL 检查,但是日期date2
并且date3
可以是 NULL 所以我想检查空值并相应地检查日期条件。我尝试了两种方法,但无法弄清楚如何正确地做到这一点。你能帮我吗?
查询一:
SELECT *
FROM
docs
WHERE
date1 < '20120601'
AND CASE
WHEN date2 IS NOT NULL AND date3 IS NOT NULL THEN date2 < '20120601'
WHEN date2 IS NOT NULL AND date3 IS NULL THEN date2 < '20120601'
WHEN date2 IS NULL AND date3 IS NOT NULL THEN date3 < '20120601'
END
这首先在以下情况下给出错误:Incorrect syntax near '<'.
我将查询修改为:
SELECT *
FROM
docs
WHERE
date1 < '20120601'
AND CASE
WHEN date2 IS NOT NULL AND date3 IS NOT NULL AND date2 < '20120601' THEN TRUE
WHEN date2 IS NOT NULL AND date3 IS NULL AND date2 < '20120601' THEN TRUE
WHEN date2 IS NULL AND date3 IS NOT NULL AND date3 < '20120601' THEN TRUE
END
并得到另一个错误:An expression of non-boolean type specified in a context where a condition is expected, near 'END'.