首页 > 解决方案 > 以表2的行数据为列标题合并两张表

问题描述

如何使用表 2 的行数据作为列标题组合两个表?

表格1:

ID 电子邮件 中间名字
2901 john@io.com 约翰 迈克尔 史密斯

表2:

ID 问题ID 回答
2901 1 多伦多
2901 2 加拿大
2901 3 9991118721

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

ID 电子邮件 中间名字 1 2 3
2901 john@io.com 约翰 迈克尔 史密斯 多伦多 加拿大 9991118721

标签: sqlsql-servertsqldynamic-sql

解决方案


你可以试试这样的

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;

推荐阅读