简体   繁体   中英

How do I create two additional fields to a view based on output from two case statements

Hi I'm looking to create two additional fields with my query. Status (ACTIVE/INACTIVE) and REASON (BAU/EXPIRY) based on criteria. Currently it is one column, but I want to split it into two. Below is the code:

select first_name,last_name,end_date as "Contract end date",date_removed,
case  
when END_DATE > sysdate and DATE_REMOVED is null then 'ACTIVE'  
when END_DATE <= sysdate then 'INACTIVE - Contract Expired' 
when DATE_REMOVED is not null then 'INACTIVE - BAU'
end 
as status
from DEPARTMENTS d inner join employees e on e.DEPARTMENT_ID = d.DEPARTMENT_ID

Want it to display

**STATUS**           **REASON**
ACTIVE           
ACTIVE           
INACTIVE         CONTRACT EXPIRY
INACTIVE         BAU
...               ...

based on your sample...

select 
case when STATUS like '%ACTIVE%' is null then '' ,
   when STATUS like '%INACTIVE%'  and DATE_REMOVED is not null then 'BAU' 
   when STAUS like '%INACTIVE%' and END_DATE <= sysdate then 'Contract Expired'
end as REASON,
case when REASON IS NULL then 'ACTIVE'
    ESLE 'INACTIVE' end as STATUS

from (


select first_name,last_name,end_date as "Contract end date",date_removed,
case  
when END_DATE > sysdate and DATE_REMOVED is null then 'ACTIVE'  
when END_DATE <= sysdate then 'INACTIVE - Contract Expired' 
when DATE_REMOVED is not null then 'INACTIVE - BAU'
end 
as status
from DEPARTMENTS d inner join employees e on e.DEPARTMENT_ID = d.DEPARTMENT_ID)

do this

     select a.*, substr(a.status,replace(instr(a.status,'-',1,1),0,LENGTH(a.status)) + 1) Reason from (select first_name,last_name,end_date as "Contract end date",date_removed,
     case  
     when END_DATE > sysdate and DATE_REMOVED is null then 'ACTIVE'  
     when END_DATE <= sysdate then 'INACTIVE - Contract Expired' 
     when DATE_REMOVED is not null then 'INACTIVE - BAU'
     end 
     as status
     from DEPARTMENTS d inner join employees e on e.DEPARTMENT_ID = d.DEPARTMENT_ID) a

I don't normally answer my own question but below was what I was looking for

select first_name,last_name,end_date,date_removed,
case  
when END_DATE > sysdate and DATE_REMOVED is null then 'ACTIVE'  
when END_DATE <= sysdate then 'INACTIVE' 
end 
as status,
case  
when END_DATE <= sysdate then 'Contract Expired' 
when DATE_REMOVED is not null then 'BAU'
end 
as Reason
from DEPARTMENTS d inner join employees e on e.DEPARTMENT_ID = d.DEPARTMENT_ID;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM