Sql 使用表2的行数据作为列标题合并两个表

Sql 使用表2的行数据作为列标题合并两个表,sql,sql-server,tsql,dynamic-sql,Sql,Sql Server,Tsql,Dynamic Sql,如何使用表2的行数据作为列标题组合两个表 表1: 身份证件 电子邮件 名字 中间名 姓氏 2901 john@io.com 厕所 迈克尔 史密斯 你可以试试这样的 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.question

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

表1:

身份证件 电子邮件 名字 中间名 姓氏 2901 john@io.com 厕所 迈克尔 史密斯
你可以试试这样的

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;

如果需要将列名动态地作为问题id的值,请仅使用动态SQL查看PIVOT/UNPIVOT函数。我个人建议你也许重新思考一下,你真的“需要”这个。如果你真的“需要”这个,那么看看。如果你不理解解决方案,那么我也建议你重新思考;除非您理解动态SQL,否则您不应该使用它。您需要向我们展示您的尝试。