sql - 以表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 |
解决方案
你可以试试这样的
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;
推荐阅读
- python - 使用 Selenium chrome 驱动程序进行 Python 网页抓取
- java - 如何使用 Firebase 的 Java Admin SDK 在单个位置更新对象而不覆盖其他字段?
- javascript - GraphQL 不允许查询不同的字段
- frameworks - 2020年我应该学习哪个Web开发框架?
- bash - unity cloud build Post-Build 脚本上传到 github 页面
- python - 无法从 kafka 主题读取\写入
- python - 从python中的空列表计算新列表的最快方法
- python - 两者如何组合两列不同的数据框,以使它们具有唯一值?
- python - Xarray:ValueError:维度或多索引级别['lons','lats']不存在
- python - 我正在使用函数开发一个石头、纸、剪刀程序,它总是返回其他情况