【问题标题】:Combine two tables using the row data of table 2 as column header以表2的行数据为列标题合并两张表
【发布时间】:2021-05-07 04:13:13
【问题描述】:

如何将表2的行数据作为列标题合并两个表?

表 1:

id email firstname middlename lastname
2901 john@io.com john michael smith

表 2:

id questionId answer
2901 1 Toronto
2901 2 Canada
2901 3 9991118721

最终结果应该是表1表头加上questionId数据作为表头,然后使用表1数据和表2答案数据作为行:

id email firstname middlename lastname 1 2 3
2901 john@io.com john michael smith Toronto Canada 9991118721

【问题讨论】:

  • 看看 PIVOT/UNPIVOT 函数
  • 如果您需要将列名动态地作为问题 ID 的值,则仅使用动态 SQL。我个人建议你或许重新考虑一下这是你真的“需要”这个。如果您确实真的“需要”这个,请参阅SQL Server dynamic PIVOT query?。如果您不了解解决方案,那么我也建议您重新考虑;除非您了解动态 SQL,否则您不应该使用它。
  • 您需要向我们展示您的尝试。

标签: sql sql-server tsql dynamic-sql


【解决方案1】:

你可以试试这样的

select t1.id, t1.email, t1.firstname, t1.middlename, t1.lastname,
       max(case when t2.questionId=1 then t2.answer else null end) 1,
       max(case when t2.questionId=2 then t2.answer else null end) 2,
       max(case when t2.questionId=3 then t2.answer else null end) 3
from table1 t1
     join table2 t2 on t1.id=t2.id
group by t1.id, t1.email, t1.firstname, t1.middlename, t1.lastname;

【讨论】:

    猜你喜欢
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    相关资源
    最近更新 更多