Home > database >  How can I use CASE to display special status cell if record exists in table 1 but not in table 2?
How can I use CASE to display special status cell if record exists in table 1 but not in table 2?

Time:11-05

I have two tables:

Table1

WIP1 TimeStamp1
1 2021-11-04
2 2021-11-04
3 2021-11-04
4 2021-11-04

And table 2

WIP2 TIMESTAMP2 Status2
1 2021-11-04 RECEIVED
2 2021-11-04 PENDING
4 2021-11-04 RECEIVED

I want to write a SELECT that display if the WIPS on table 1 already exists on table 2, if not, display a respective message (keeping the Table 2 message, i.e. pending or received and adding a message 'Not Received' if the WIP doesn't exist on Table 2), so, with the columns from my example:

WIPR TIMESTAMPR Status
1 2021-11-04 RECEIVED
2 2021-11-04 PENDING
3 2021-11-04 NOT RECEIVED
4 2021-11-04 RECEIVED

Right now I've tried the following query:

select 
    t.WIP, t.TimeStamp, t.Operation 
from 
    Table1 w
join 
    Table2 t on t.WIP = w.WIP
union
select 
    w.WIP, w.DateaReleased, 'Not Received' operation 
from 
    Table1 w
left join 
    Table2 t on t.WIP = w.WIP

And it kind of works, but it duplicates the records:

enter image description here

CodePudding user response:

You can use left join and case, like below

select t1.wip1 as wipr, t2.TimeStamp2, 
       case when t2.wip2 is null then 'NOT RECEIVED' else t2.status2 end as status
from Table1 t1
left join Table2 t2 on t1.wip1 = t2.wip2

CodePudding user response:

Just an alternative to @Farshid Shekari 's answer.

You can also use Coalesce:

select t1.wip1 as wipr
      ,t1.TimeStamp1 as timestampr
      ,coalesce(t2.status2, 'not received')
from Table1 t1
left join Table2 t2 on t1.wip1 = t2.wip2
  • Related