简体   繁体   中英

Select a specific column in SQL Server from a concatenation from a different table

I'm trying to select a specific column based off a value in another table

I have one table with the following columns:

TableA :

Item_Id,Column01,Column02,Column03,Column04,Column05,  

Sample data for TableA respectively:

1,$1.00,$2.00,$3.00,$4.00,$5.00

TableB columns:

 Item_ID,Column  

Data for TableB :

1,05

I want to be able to return the value based on what I have in TableB . Currently I'm concatenating to get the field name, but I don't know how to get the value.

Select 'Column'+TableB.[Column] 
from TableA 
inner join TableB on TableA.Item_Id = TableB.ItemB
WHERE TableA.Item_Id = 1

So for this particular example the query would select column05 from TableA and the result would be $5.00.

You can use the CASE statament

Select CASE TableB.[Column] When '01' THEN TableA.Column01
                            When '02' THEN TableA.Column02
                            When '03' THEN TableA.Column03
                            When '04' THEN TableA.Column04
                            When '05' THEN TableA.Column05
       END as Value
from TableA 
inner join TableB on TableA.Item_Id = TableB.ItemB
WHERE TableA.Item_Id = 1

But the column01 ... column05 of tableA need to be of the same data type, or converted to the same data type.

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