首页 > 解决方案 > 将两个具有 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

标签: sqlsql-server-2008

解决方案


你想要一个默认值。您可以使用两个left joins:

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;

推荐阅读