sql - 将两个具有 NULL 的表连接为通用数据
问题描述
我有两个表,一个有事实数据(Table1),另一个是一个维度,其中包含第一个表(维度)的值。Dimension 表使用 null 作为通用值。
我知道我可以使用临时表和两次更新来“加入”,但我认为必须有更好的方法。我该如何加入?
谢谢
Table1: Dimension:
Col1: Code1 Code2: Code1: Code2: Value
a 1 12 1 12 5
b 1 15 1 15 6
c 1 16 1 16 7
d 1 17 1 <null> 9
e 1 20
ResultTable
Col1: Code1 Code2 Value
a 1 12 5
b 1 15 6
c 1 16 7
d 1 17 9
e 1 20 9
解决方案
你想要一个默认值。您可以使用两个left join
s:
select a.*, coalesce(b.value, bdefault.value) as value
from a left join
b
on a.code2 = b.code2 left join
b bdefault
on bdefault.code2 is null;
另一个有趣的方法使用outer apply
:
select a.*, b.value
from a outer apply
(select top (1) b.value
from b
where b.code2 = a.code2 or b.code2 is null
order by (case when b.code2 is not null then 1 else 2 end)
) b;
推荐阅读
- hibernate - 休眠查询导致 Oracle 中缺少表达式
- sql-server - 为每个 SQL Server 女巫 ClickOnce 部署 Microsoft 系统 CLR 类型时出错
- java - 如何将用户函数添加到从 JasperCompilerManager 编译的 jrxml
- django - 查询集只允许我在连接中选择一个表字段
- kotlin - kotlin 多平台到 javascript:不尊重方法的命名
- ruby-on-rails - 如果记录以前不存在,update_attribute 在 first_or_create 之后不做任何事情
- angular - Visual Studio 在构建过程中截断我的 HTML 文本
- python - UTF-8 解码 ANSI 编码文件会引发错误
- ios - Microsoft for Xamarin Forms 的 active-directory-xamarin-native-v2 示例项目在 iOS 中不起作用
- javascript - 如何在带有字符串对象的 parseJson 函数中使用变量?