Bipin Babu
Bipin Babu

Reputation: 91

SQL Dynamic column value allocation from column name reference

Input table looks as below which has various conversions, but reported only on one conversion (defined in report_field) enter image description here

Output table has reported_conversion which is derived based on report_field enter image description here

What's the best way of coding to achieve this?

Upvotes: 0

Views: 68

Answers (1)

Lukasz Szozda
Lukasz Szozda

Reputation: 176124

CASE expression could be used:

SELECT *
     ,CASE report_field 
           WHEN 'conversion1' THEN conversion1
           WHEN 'conversion2' THEN conversion2
           WHEN 'conversion3' THEN conversion3
      END AS reported_conversion       
FROM tab;

or DECODE

SELECT *, DECODE(report_field,
                 'conversion1', conversion1
                 'conversion2', conversion2
                 'conversion3', conversion3)
FROM tab

Upvotes: 1

Related Questions