简体   繁体   English

将一个表中的列值连接到另一个表的新列中的行

[英]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 COL01 25 25
COL02 COL02 71 71
COL03 COL03 13 13

The same row values listed under the KEY column from table 1 are the column names for table 2.表 1 的 KEY 列下列出的相同行值是表 2 的列名。

COL01 COL01 COL02 COL02 COL03 COL03
XX XX YY YY ZZ Z Z

Desired result:期望的结果:

KEY钥匙 VALUE价值 NEW_COL NEW_COL
COL01 COL01 25 25 XX XX
COL02 COL02 71 71 YY YY
COL03 COL03 13 13 ZZ Z Z

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.

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