简体   繁体   中英

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!)

  • 21 of the columns in this table stand for 'Actual' sizes
  • 21 of the columns in this table stand for 'Relative' sizes
  • The Actual size columns correspond through Relative size columns via column number.
    (ex : corresponds to , corresponds to , up to 21) 对应于对应于到RelativeColumnX多达21)

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM