仅当满足条件时,WHERE子句中的Oracle SQL CASE表达式

时间:2016-01-14 12:18:50

标签: sql oracle

不能完全理解这一个,我有一套条件,只有当一个值在一个字段中时我才能满足。

因此,如果状态完成,我希望有三个where子句,如果状态不等于完成,那么我不想要任何where子句。

代码

SELECT *
FROM mytable
WHERE CASE WHEN Status = 'Complete'
           THEN (included = 0 OR excluded = 0 OR number IS NOT NULL)
           ELSE *Do nothing*

3 个答案:

答案 0 :(得分:4)

WHERE中仅使用布尔表达式通常很简单。所以:

WHERE (Status <> 'Complete') OR 
      (included = 0 OR excluded = 0 OR number IS NOT NULL)

如果Status可能是NULL

WHERE (Status <> 'Complete' OR Status IS NULL) OR 
      (included = 0 OR excluded = 0 OR number IS NOT NULL)

答案 1 :(得分:3)

您可以在SQL中翻译自然语言,然后,如果可能,重新制定。

SELECT *
FROM mytable
WHERE (Status = 'Complete' and (included = 0 OR excluded = 0 OR number IS NOT NULL)) 
     or status <> 'Complete'
     or status IS NULL;

答案 2 :(得分:1)

看起来你真的不需要CASE语句,只需像这样使用它:

SELECT *
FROM mytable
WHERE where (Status = 'Complete' and (included = 0 OR excluded = 0 OR number IS NOT NULL)) or (*Your do nothing*)