sql - SQL Server 表中无数据时显示空值
问题描述
我有表格和查询来从行到列选择数据,如下所示:
id | type | data
-----------------------
1 | Name | John
1 | Gender | Male
1 | Code | 1782
2 | Name | Dave
2 | Gender | Male
询问 :
select a.id, a.data as [Name], b.data as [Gender], c.data as [Code]
from table1 a join table1 b on a.id = b.id
join table1 c on b.id = c.id
where a.type = 'Name' and b.type = 'Gender' and c.type = 'Code'
结果 :
id | Name | Gender | Code
------------------------------
1 | John | Male | 1782
在这种情况下,名为“Dave”的 ID 号 2 没有“代码”,因此它不会出现在结果中。我怎样才能在“代码”表上显示带有空数据或 NULL 的结果,所以它会有这样的结果:
id | Name | Gender | Code
------------------------------
1 | John | Male | 1782
2 | Dave | Male |
解决方案
select a.id, a.data as [Name], b.data as [Gender], c.data as [Code]
from table1 a
left join table1 b on a.id = b.id and b.type='Gender'
left join table1 c on b.id = c.id and c.type='Code'
where a.type = 'Name'
推荐阅读
- android - 如何返回由 NavHostFragment 控制的 Fragment 内的 WebView?
- git - 如何让成员完成 Git 日志
- r - 基于部分字符串匹配合并来自另一个数据帧的值,而匹配列的顺序不同
- tcl - 在列表中传递变量并期望其文字值
- node.js - Nodejs 猫鼬 | findOneAndUpdate 无法正常工作
- mongodb - 将mongodb数据导入mongo镜像
- java - 在 Android 上运行 shell 命令不会返回任何内容
- node.js - 使用 Nodejs Spawn 启动 Linux 屏幕会话
- mysql - 如何使用node js更新mysql中的多行
- flutter - 如何在颤动中将文本与图像对齐?