Sonu
Sonu

Reputation: 65

Need an SQL query to map column value to column name

I have following table structure (Table Name is Questions)

c1   c2   c3  Selection

X    Y    Z   2

A    B    C   3

Here c1,c2,c3 and Selection are column names. I want to retrieve value of c1 or c2 or c3 on the basis of value of column Selection. Eg. If Selection value is 2 then I want corresponding value of c2 column i.e. Y. If Selection value is 3 then it should select value of c3 column which is C here.

Please help me in forming Select Sql query here. I tried myself but was not able to find correct solution.

Thanks in advance

Upvotes: 1

Views: 4881

Answers (3)

sourcecode
sourcecode

Reputation: 1802

you have to use CASE's or IF's

   select if(selection=2 ,b,if(selection=3,c,a)) from Table1 ;

see here for example ... link

Upvotes: 2

John Woo
John Woo

Reputation: 263703

SELECT  CASE Selection
            WHEN 1 THEN c1
            WHEN 2 THEN c2
            ELSE c3
        END val
FROM    tableName

Upvotes: 2

Muhammad Raheel
Muhammad Raheel

Reputation: 19882

This is very simple just run a simple query and it will return all the columns then you should use the appropriate column.

SELECT * FROM mytable WHERE selection = 'yourvalue'

Upvotes: 0

Related Questions