Futochan
Futochan

Reputation: 331

IF ELSE Statement and Insert a new Column

I've been trying research online on how to combine "If" statements into my query. Suppose I wanted to create a query such that I want to create a extra column called "Description", and then include a if else statement such that "If Value = "A" then Description = "A", If Value = "B" then Description = "B", so on and so on. The problem is, since I have minimal access (not admin) to the databases. I can't create tables. I can only query the tables in oracles and export it out. Will that be an issue in terms of creating an extra column?

Original:

ID Value  
1  A  
2  B   
3  C

Want something like:

ID Value Description(New Column)  
1  A     Apple  
2  B     Bacon  
3  C     Candy

Okay. I have no idea what I was doing below but it would be something like that? Where to I insert a new column called "Description"?

Select A.ID, B.Value  
From Table A  
Join Table B  
On A.ID = B.ID  
Where ID in ('1','2','3')  
If b.Value = 'A' then  
   (Description = "Apple")  
If b. value = 'B' then  
   (Description = "Bacon")
Group by A.ID, B.Value

Upvotes: 6

Views: 45184

Answers (3)

Bacs
Bacs

Reputation: 919

I'm not sure why you need to join the table to itself. Also, I presume you're not really trying to do this with a table named "table".

CASE would do the job, as in Barmar's answer. I find DECODE more readable when the logic is this simple, but it's really a matter of taste. CASE is more flexible, which is not a matter of taste, but you don't need that flexibility here.

select  id
       ,value
       ,decode( value
                 ,'A', 'Apple'
                 ,'B', 'Bacon'
                 ,'C', 'Candy' ) as Description
from table;

Upvotes: 0

Barmar
Barmar

Reputation: 780889

You can use CASE:

SELECT A.ID, B.Value,
       CASE B.Value
            WHEN 'A' THEN 'Apple'
            WHEN 'B' THEN 'Bacon'
            WHEN 'C' THEN 'Candy'
       END AS Description
FROM TableA A
JOIN TableB B ON A.ID = B.ID

Upvotes: 16

radar
radar

Reputation: 13425

you can do it like below

SELECT A.ID, A.Value, B.Description
FROM TABLEA A
JOIN ( SELECT 'A' as Value, 'Apple' as Description from dual
       UNION
       SELECT 'B' as Value, 'Bacon' as Description from dual
     ) T
on A.Value= B.Value

Upvotes: 1

Related Questions