[英]Join column values from one table to rows in new column on another table
I am trying to write a SQL query in SQL Server 2008 that will match the column values from a single query into a new column on a table where the column headers are stored as row values.我正在尝试在 SQL Server 2008 中编写 SQL 查询,它将单个查询中的列值匹配到表上的新列中,其中列标题存储为行值。
I have two queries:我有两个疑问:
KEY![]() |
VALUE![]() |
---|---|
COL01 ![]() |
25 ![]() |
COL02 ![]() |
71 ![]() |
COL03 ![]() |
13 ![]() |
The same row values listed under the KEY column from table 1 are the column names for table 2.表 1 的 KEY 列下列出的相同行值是表 2 的列名。
COL01 ![]() |
COL02 ![]() |
COL03 ![]() |
---|---|---|
XX ![]() |
YY ![]() |
ZZ ![]() |
Desired result:期望的结果:
KEY![]() |
VALUE![]() |
NEW_COL ![]() |
---|---|---|
COL01 ![]() |
25 ![]() |
XX ![]() |
COL02 ![]() |
71 ![]() |
YY ![]() |
COL03 ![]() |
13 ![]() |
ZZ ![]() |
Hmmm.嗯。 .
. .
. I would suggest unpivoting and joining:
我建议取消旋转并加入:
select t1.*, t2.val
from table2 t2 cross join
(values (t2.col01, 'col01'), (t2.col02, 'col02'), (t2.col03, 'col03')
) v(val, which) join
table1 t1
on t2.which = t1.key;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.