2

I have a table lets say

Table1

t_id A   B  C

100  1   1  0

101  1   0  1

102  1   1  0

Now I have input parameter param0 based on which first I have to select column (lets say B) and then using t_id value(lets say 101) i will be selecting value of that selected column(which is 0).

I want to create single query as i will be using it in join query.

Is above possible, if yes how to write the sql for same?

Ajhar Shaikh
  • 1,106
  • 2
  • 14
  • 33

2 Answers2

2

This is valid for SQL server. I am not sure if this will work in mySQL You can do this easily by unpivoting the data and then selecting column and tid using parameters in where clause For MySql you should probably look into this article on stackoverflow

SELECT Colvalue FROM (
SELECT t_id, ColName, ColValue
FROM 
   (SELECT t_id,A,B,C FROM tablename) t
UNPIVOT
   (Colvalue FOR ColName IN  (A,B,C) )AS unpvtt) 
WHERE t_id=@paramTid AND Colname=@paramColname
Community
  • 1
  • 1
DhruvJoshi
  • 17,041
  • 6
  • 41
  • 60
2

In MySQL, this is most easily done with a case statement:

select (case when @param0 = 'A' then A
             when @param0 = 'B' then B
             when @param0 = 'C' then C
        end) as val
from table t
where id = @t_id;

Actually, it is most easily done with a case statement in almost any database.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786