Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 使用字段中存储的列的名称从其他表检索数据_Sql_Sql Server_Unpivot - Fatal编程技术网

Sql 使用字段中存储的列的名称从其他表检索数据

Sql 使用字段中存储的列的名称从其他表检索数据,sql,sql-server,unpivot,Sql,Sql Server,Unpivot,我想知道在SQLServer2008中是否存在可以完成以下任务的代码 表1: id column name ------------------- 1 col1 2 col2 3 col3 4 col2 表2: col1 col2 col3 -------------------- a b c 结果表: id data -------------------- 1 a 2 b 3 c 4

我想知道在SQLServer2008中是否存在可以完成以下任务的代码

表1:

id    column name
-------------------
1     col1
2     col2
3     col3
4     col2
表2:

col1    col2    col3
--------------------
a       b       c
结果表:

id    data
--------------------
1     a
2     b
3     c
4     b

提前谢谢,我真的不知道该怎么做。

我看不出没有列连接你该怎么做:

Table1:
ID
ColumnName

Table2:
Table1ID
Letter


Select table1.id, table2.Letter 
from table1 
inner join table2 on table1.ID = table2.Table1ID

您可以使用
UNPIVOT
table2
访问以下列中的数据:

select t1.id, t2.value
from table1 t1
left join 
(
  select value, col
  from table2
  unpivot
  (
    value
    for col in (col1, col2, col3)
  ) u
) t2
  on t1.name = t2.col
看见 或者您可以使用
UNION ALL
访问
表2中的数据:

select t1.id, t2.value
from table1 t1
left join 
(
  select col1 value, 'col1' col
  from table2
  union all
  select col2 value, 'col2' col
  from table2
  union all
  select col3 value, 'col3' col
  from table2
) t2
  on t1.name = t2.col

请参见您可以使用case语句和交叉连接来执行此操作:

select t1.id,
       (case when t1.columnname = 'col1' then t2.col1
             when t1.columnname = 'col2' then t2.col2
             when t1.columnname = 'col3' then t2.col3
        end) as data
from table1 t1 cross join
     table2 t2

我不完全确定你要做什么,所以我就把这个扔出去:看看
pivot
。但是,如果你想动态地做事情,你可能必须使用一些动态sql()非常感谢!当我不知道如何处理这个问题时,这两个例子都非常有用。