我想在select query
中应用以下条件。
IF (TYPE = MBUSA or SDSA or MDSA OR PC) and (FINAL_STATUS = ACTIVE OR EXECUTED)
then GET ID and Parent_ID
ELSEIF (TYPE = MSA) and (FINAL_STATUS = ACTIVE OR EXECUTED)
then GET ID---(USING the ID from the else if condition AS FILTER,
IF TYPE = (DSA OR BUSA) AND (FINAL_STATUS = ACTIVE OR EXECUTED)
then GET ID and Parent_ID)
我是否需要编写程序?
以下是数据库结构:
答案 0 :(得分:5)
CASE
语句可以用作IF.. THEN... ELSE...
语句的等效语句。不太确定你是如何选择它们的,因为你的问题不清楚,所以这里有一些建议。
使用条件格式的字符串表示选择单个列:
SELECT
CASE
WHEN (TYPE IN ('MBUSA','SDSA','MDSA','PC') AND (FINAL_STATUS IN ('ACTIVE','EXECUTED'))
THEN ID + ' ' + P_ID
WHEN ((TYPE = 'MSA') AND (FINAL_STATUS IN ('ACTIVE','EXECUTED'))
THEN ID
WHEN (TYPE IN ('DSA','BUSA') AND (FINAL_STATUS IN ('ACTIVE','EXECUTED'))
THEN ID + ' ' + P_ID
ELSE ''
END AS columnName
FROM
tableName
将每个选择成单独的列
SELECT
CASE
WHEN (TYPE IN ('MBUSA','SDSA','MDSA','PC') AND (FINAL_STATUS IN ('ACTIVE','EXECUTED'))
THEN ID
WHEN ((TYPE = 'MSA') AND (FINAL_STATUS IN ('ACTIVE','EXECUTED'))
THEN ID
WHEN (TYPE IN ('DSA','BUSA') AND (FINAL_STATUS IN ('ACTIVE','EXECUTED'))
THEN ID
ELSE ''
END AS columnOneName
CASE
WHEN (TYPE IN ('MBUSA','SDSA','MDSA','PC') AND (FINAL_STATUS IN ('ACTIVE','EXECUTED'))
THEN P_ID
WHEN ((TYPE = 'MSA') AND (FINAL_STATUS IN ('ACTIVE','EXECUTED'))
THEN NULL
WHEN (TYPE IN ('DSA','BUSA') AND (FINAL_STATUS IN ('ACTIVE','EXECUTED'))
THEN P_ID
ELSE ''
END AS columnTwoName
FROM
tableName
虽然看上面的内容(我可能错误地转录了你的逻辑)但是当你可以逃脱2时有三种情况说明:
CASE
WHEN (TYPE IN ('MBUSA','SDSA','MDSA','PC','DSA','BUSA') AND (FINAL_STATUS IN ('ACTIVE','EXECUTED'))
THEN ID + ' ' + P_ID
WHEN ((TYPE = 'MSA') AND (FINAL_STATUS IN ('ACTIVE','EXECUTED'))
THEN ID
ELSE ''
END AS columnName
我知道你现在已经放了一个截图,但SQL Fiddle可能会更有帮助或更详细,以便表名等可以很容易
有用的链接:
答案 1 :(得分:0)
您可以使用CASE在PL / SQL中实现IF-THEN-ELSE - 这只是一个例子:
select case field1 WHEN '1' THEN 'VALUE1'
WHEN '2' THEN 'VALUE2'
ELSE 'VALUEOTHER'
END,
case field2 WHEN '1' THEN 'VALUE1'
WHEN '2' THEN 'VALUE2'
ELSE 'VALUEOTHER'
END
from (
select '1' "FIELD1",
'2' "FIELD2"
from dual
);
您不能在多列上使用CASE语句;但是,如果你需要比较 在同一个CASE语句中的多个字段,您可以使用这样的解决方法:
select case field1 || '_' || field2
WHEN '1_1' THEN 'FIELD1-IS-VALUE1 AND FIELD2-IS-VALUE1'
WHEN '1_2' THEN 'FIELD1-IS-VALUE1 AND FIELD2-IS-VALUE2'
WHEN '2_1' THEN 'FIELD1-IS-VALUE2 AND FIELD2-IS-VALUE1'
WHEN '2_2' THEN 'FIELD1-IS-VALUE2 AND FIELD2-IS-VALUE2'
ELSE 'VALUEOTHER'
END
from (
select '1' "FIELD1",
'2' "FIELD2"
from dual
);
如果SQL语句变得难以阅读,最好使用带有SQL语句的视图或使用PL / SQL。
参考文献: