Chris1804505
Chris1804505

Reputation: 97

Need to find value in one column and then return value from another column

Here is my problem. I have a Microsoft SQL server database table with a bunch of columns in it. (I cannot change the data structure of this table!)

Based on the inputted 'Actual' value I need to return the related 'Relative' value.

I have managed to do part of what I need with the following case statement, but case statements have a maximum of 10 conditions and therefore won't be able to cover all 21 columns in my table. What would be the best way to approach this issue? My goal would be to put this into a select statement so that I could select the Relative Size and return it in my query.

Example of what I did with the case statement:

SELECT
    T.AValue
    CASE WHEN (T.ActualColumn1 = T.AValue) then T.RelativeColumn1 ELSE
        CASE WHEN (T.ActualColumn2 = T.AValue) THEN T.RelativeColumn2 ELSE
            CASE WHEN (T.ActualColumn3 = T.AValue) THEN T.RelativeColumn3 ELSE
                CASE WHEN (T.ActualColumn4 = T.AValue) THEN T.RelativeColumn4 ELSE
                    NULL
                END 
            END 
        END 
    END AS RValue
FROM T

Thank you for your help!

Upvotes: 1

Views: 3233

Answers (1)

Mikael Eriksson
Mikael Eriksson

Reputation: 138970

If you change your case statement to a searched case you can have more then 10 when clauses.

select T.AValue,
       case T.AValue
         when T.ActualColumn1 then T.RelativeColumn1
         when T.ActualColumn2 then T.RelativeColumn2
         when T.ActualColumn3 then T.RelativeColumn3
         when T.ActualColumn4 then T.RelativeColumn4
       end as RValue
from T

Upvotes: 3

Related Questions