0

我需要编写一个这样的查询:

Select [something]
Where
condition in
case
when (if another_condition = A and 3rd Condition = B) then (C,D)
when (if another_condition = N and 3rd Condition = E) then (F,G)
else (J,K)
end

本质上,我想要的是如果满足 A 和 B,条件可以设置为 C 或 D,如果满足 N 或 E,则条件可以设置为 F 或 G,否则条件设置为 J 或 K。但是,当我运行它时,我在关键字“Case”附近不断收到不正确的语法。

请帮忙!谢谢!

4

3 回答 3

2

也许是这样:

Where  (Another_Condition = 'A' And Third_Condition = 'B' And Condition in ('C','D'))
       Or 
       (Another_Condition = 'N' and Third_Condition = 'E' And Condition in ('F','G'))
       Or 
       Condition In ('J','K')

在 where 子句中混合 and's 和 or's 时要非常小心。括号很重要。

于 2010-08-11T13:22:48.850 回答
1

怎么样 - UNION 子查询将为您提供子查询中的完整结果集。然后你可以说'WHERE condition IN'(子查询)。像这样:

SELECT [something]
WHERE
condition IN
(SELECT CASE WHEN (another_condition = A AND 3rd Condition = B) THEN C
   WHEN (another_condition = N AND 3rd Condition = E) THEN F
   ELSE J
   END AS Value

UNION

SELECT CASE WHEN (another_condition = A AND 3rd Condition = B) THEN D
   WHEN (another_condition = N AND 3rd Condition = E) THEN G
   ELSE K
   END AS Value
)
于 2010-08-11T13:17:49.890 回答
1

我可能会采用 G Mastro 将查询扩展为布尔表达式的方法。虽然嵌套查询方法会起作用,但代码的意图不太明显 IMO。

Having said that, if there are a lot of cases in your CASE statement, you may want to consider reshaping your data, because no matter how you write the query, it boils down to a big Boolean expression.

于 2010-08-11T14:01:09.233 回答