【问题标题】:Join column values from one table to rows in new column on another table将一个表中的列值连接到另一个表的新列中的行
【发布时间】:2023-03-06 14:20:01
【问题描述】:

我正在尝试在 SQL Server 2008 中编写一个 SQL 查询,它将单个查询中的列值匹配到表上的新列中,其中列标题存储为行值。

我有两个疑问:

KEY VALUE
COL01 25
COL02 71
COL03 13

表 1 的 KEY 列下列出的相同行值是表 2 的列名。

COL01 COL02 COL03
XX YY ZZ

想要的结果:

KEY VALUE NEW_COL
COL01 25 XX
COL02 71 YY
COL03 13 ZZ

【问题讨论】:

  • 您为什么使用不受支持的软件?
  • 请向我们展示您目前的尝试。

标签: sql sql-server sql-server-2008


【解决方案1】:

嗯。 . .我建议取消透视并加入:

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-19
    • 2010-10-20
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多