CASE .. WHEN在Oracle SQL中expression

我有1列的表,并有以下数据

Status a1 i t a2 a3 

我想在我的select查询中显示以下结果

 Status| STATUSTEXT a1 | Active i | Inactive t | Terminated a2 | Active a3 | Active 

我能想到的一种方法是在select查询中使用Switch Whenexpression式

 SELECT status, CASE status WHEN 'a1' THEN 'Active' WHEN 'a2' THEN 'Active' WHEN 'a3' THEN 'Active' WHEN 'i' THEN 'Inactive' WHEN 't' THEN 'Terminated' END AS StatusText FROM stage.tst 

有没有其他方式可以在不需要写入的情况下在一个expression式中可以检查活动状态的3次expression式和整个活动状态?

你可以使用一个IN子句

就像是

 SELECT status, CASE WHEN STATUS IN('a1','a2','a3') THEN 'Active' WHEN STATUS = 'i' THEN 'Inactive' WHEN STATUS = 't' THEN 'Terminated' END AS STATUSTEXT FROM STATUS 

看看这个演示

SQL小提琴演示

当然…

 select case substr(status,1,1) -- you're only interested in the first character. when 'a' then 'Active' when 'i' then 'Inactive' when 't' then 'Terminated' end as statustext from stage.tst 

但是,这个模式有一些令人担忧的地方。 首先,如果你有一个列意味着什么,那么附加一个数字就不一定是最好的方法。 此外,根据状态的数量,您可能需要考虑将此列转换为单独的表中的外键。


根据你的评论,你一定要把它变成一个外键。 例如

 create table statuses ( -- Not a good table name :-) status varchar2(10) , description varchar2(10) , constraint pk_statuses primary key (status) ) create table tst ( id number , status varchar2(10) , constraint pk_tst primary key (id) , constraint fk_tst foreign key (status) references statuses (status) ) 

您的查询然后成为

 select a.status, b.description from tst a left outer join statuses b on a.status = b.status 

这是一个SQL小提琴演示。

您可以重写它以使用CASE的ELSE条件:

 SELECT status, CASE status WHEN 'i' THEN 'Inactive' WHEN 't' THEN 'Terminated' ELSE 'Active' END AS StatusText FROM stage.tst 

您只能检查状态的第一个字符。 为此,您使用子string函数。

substr(status,1,1)

在你的情况过去。

以下语法将工作:

 .... where x.p_NBR =to_number(substr(y.k_str,11,5)) and x.q_nbr = (case when instr(substr(y.m_str,11,9),'_') = 6 then to_number(substr(y.m_str,11,5)) when instr(substr(y.m_str,11,9),'_') = 0 then to_number(substr(y.m_str,11,9)) else 1 end ) 

使用解码会更容易。

 SELECT status, decode ( status, 'a1','Active', 'a2','Active', 'a3','Active', 'i','Inactive', 't','Terminated', 'Default')STATUSTEXT FROM STATUS 
 SELECT STATUS, CASE WHEN STATUS IN('a1','a2','a3') THEN 'Active' WHEN STATUS = 'i' THEN 'Inactive' WHEN STATUS = 't' THEN 'Terminated' ELSE null END AS STATUSTEXT FROM stage.tst;