我的问题是在where子句中使用case语句来检查日期并为列分配值。我的示例代码包括。
select * from table
where
column 1 > 10 and
case when column 2 = 1
then
column 3<= 10 and column 4 between (1st day of prev month) and (prev month end) or column 5 = '8888-01-01'
else
column 4 between (1st day of this month) and (yesterday)
end ;
当我运行此代码时。我收到了3706语法错误:期望在字段和&#39; =&#39;。
之间如何解决这个问题?
答案 0 :(得分:0)
CASE语句将始终返回值或NULL(如果没有条件匹配),因此您可以在WHERE子句中使用它。有几种方法可以格式化CASE语句:
格式1
CASE
WHEN <condition> THEN <some_expression>
WHEN <another_condition> THEN <another_expression>
ELSE <final_expression>
END
-- Example
CASE
WHEN col1 = 10 THEN 'Y'
WHEN col1 = 20 THEN 'N'
ELSE 'N/A'
END
格式2
CASE <expression>
WHEN <value> THEN <expression>
WHEN <another_value> THEN <another_expression>
ELSE <final_expression>
END
-- Example
CASE col1
WHEN 10 THEN 'Y'
WHEN 20 THEN 'N'
ELSE 'NA'
END
我不确定您尝试使用示例代码做什么,但它看起来更像伪代码,不会按原样运行。您的CASE语句格式不正确,而column 1
之类的列引用将无法正常工作。如果您的列实际上名为column 1
,那么您需要在其周围添加双引号:
select * from table where "column 1" > 10
你能否更清楚地描述一下你究竟要做什么?
答案 1 :(得分:0)
CASE表达式不能用于创建某种动态条件。把它写成一堆AND / OR条件:
select * from table
where
column 1 > 10 and
(
( column 2 = 1 and
(column 3<= 10 and column 4 between (1st day of prev month) and (prev month end) or column 5 = '8888-01-01')
)
or
column 4 between (1st day of this month) and (yesterday)
);
仔细检查逻辑,逻辑运算符的优先级是