Question

If it is possible, I want to return another column that contains the name of the column where the variable is found (CH1, CH2 or CH3).

Something like:

v1 => ch3

v2 => ch1

This is my query:

SELECT variable
FROM Variables , Names
WHERE (Variables.ID = Names.Ch1 or  Variables.ID = Names.Ch2 or Variables.ID = Names.Ch3 ) 

The format of my tables:

Names(#ID,Ch2,Ch2,Ch3)
Variables(#ID, variable,...)

I tried with %columName% but I get an error.

Was it helpful?

Solution

The correct syntax is more like:

select v.*,
       (case when v.id = n.ch1 then 'CH1'
             when v.id = n.ch2 then 'CH2'
             when v.id = n.ch3 then 'CH3'
        end) as WhichColumn
from variables v join
     names n
     on v.ID  in (n.Ch1, n.ch2, n.ch3)

In other words, you have to explicitly put in the logic for the column names.

OTHER TIPS

try using the LIKE if the variables ID are NOT only INT number

SELECT variable
FROM Variables , Names
WHERE 
(Variables.ID like '%Names.Ch1%' 
or  Variables.ID  like '%Names.Ch2%' 
or Variables.ID like '%Names.Ch3%' )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top