2

I have a table named t,

focus, H, Li, Be, B, C
    H, 1,  2,  3, 4, 5      
   Be, 6,  7,  8, 9, 10

I want to write a MySQL query to select columns in this table based on the values of focus column, for example, from table t it will return:

H, Be 
1, 3
6, 8

I know it's very easy to write:

select H, Be from t

However, this is not a dynamic resolution if the content of table t changed. For example, assuming table t now is:

 focus, H, Li, Be, B, C
     B, 5,  0,  0, 4, 4      
     C, 8,  9,  1, 7, 3

Previous code doesn't work. It still returns the same result instead of:

B, C      
4, 4
7, 3

My question is, is it possible, we wrote a MySQL script to select the columns based on the values of focus column?

Judah Flynn
  • 544
  • 1
  • 8
  • 20
  • This table design makes little sense to me. I guess what you want is a kind of dynamic pivot, so you should be able to find help in [this question](https://stackoverflow.com/questions/12004603/mysql-pivot-row-into-dynamic-number-of-columns) – Barmar Apr 13 '18 at 18:39
  • You can't do this in SQL, it has to be done in a stored procedure to generate a dynamic query. – Barmar Apr 13 '18 at 18:40
  • Possible [XY Problem](http://xyproblem.info/)? What are you really trying to accomplish with this? I'm with Barmar. I don't understand your table design, either. – Eric Brandt Apr 13 '18 at 19:46

1 Answers1

0

instead os selected the column based on focus value, why do you select focus based on the column. See the below example

Declare @sql varchar(10),@SQLString varchar(100)
Set @SQL = ‘H’

Set @SQLString  = ‘Select focus, ‘+@sql +
‘From tablet
Where focus = ‘+@SQL

Exec @SQLString  
SQLHelp
  • 41
  • 4