[英]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
: TableA
:
Item_Id,Column01,Column02,Column03,Column04,Column05,
Sample data for TableA
respectively: TableA
样本数据分别为:
1,$1.00,$2.00,$3.00,$4.00,$5.00
TableB
columns: TableB
列:
Item_ID,Column
Data for TableB
: TableB
数据:
1,05
I want to be able to return the value based on what I have in TableB
. 我希望能够基于
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. 因此,对于此特定示例,查询将从
TableA
选择column05,结果将为5.00美元。
You can use the CASE statament 您可以使用CASE策略
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. 但是tableA的column01 ... column05必须具有相同的数据类型,或转换为相同的数据类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.