Ashish Pratap
Ashish Pratap

Reputation: 479

How to write a SQL query which populate a column on conditional basis, from two of the existing column

Let's say there are three columns

TYPE    COUNT1  COUNT2
----------------------
A        20      -
B         -      33
B         -      41
A        32       -
B         -      45

So here we have values in COUNT1 only if TYPE = 'A', and Values in COUNT2 only for Type = 'B'

I want to write a query which can give me following output.

COUNT1/COUNT2   TYPE
--------------------
20              A
33              B
41              B
32              A
45              B

Upvotes: 0

Views: 41

Answers (1)

Fahmi
Fahmi

Reputation: 37473

Use coalesce function if column value is null:

select type,coalesce(A,B)
from tablename

Or use CASE WHEN if value is literal like '-'

select type, case when type='A' then count1 when type='B' then count2 end as value
from tablename

Upvotes: 2

Related Questions