Kirill Drozdov
Kirill Drozdov

Reputation: 39

DB2 Select from not empty columns with column name

I have a table with the following data in the DB2:

Location|Phone|Email  |Changedatetime
null    |3314 |null   |12/07/2019 10:00
null    |null |[email protected]|12/07/2019 11:00

It is a list of changes in the related table. I need a select based on this table with not null column name and value

I need to select it the following way if possible:

Attribute|Value  |Changedatetime
Phone    |3314   |12/07/2019 10:00
Email    |[email protected]|12/07/2019 11:00

Upvotes: 1

Views: 3386

Answers (2)

Satya
Satya

Reputation: 583

Use case statement.

select 
case when Phone is not null then 'Phone' else 'Email' end as Attribute , 
case when Phone is not null then Phone  else Email end as Value ,
Changedatetime
from tablename

Upvotes: 1

Fahmi
Fahmi

Reputation: 37493

One way could be to use union

select 'Phone' as attribute, Phone as value, Changedatetime
from tablename where phone is not null
union 
select 'Email', email, Changedatetime
from tablename where email is not null

Upvotes: 1

Related Questions