连接定义中的Teradata通配符

时间:2019-02-19 12:22:32

标签: sql teradata

我已经加入了波纹管这样的表:

select a.*, b.col4, b.col5 from table a
inner join table b
on  a.col2=b.col2
and a.col3=b.col3

在b.col2中可能会出现b.col3可以是值'*',这应该类似于通配符,meininng,在这种情况下,我们可以将b.col2的值连接到a.col2的任何值上或任何值a.col3的值b.col3。

您能帮我定义一下吗?

1 个答案:

答案 0 :(得分:1)

听起来您有默认设置。一种方法是多重比较:

select a.*,
       coalesce(b.col4, bdef3.col4, bdef2.col4, bdef.col4) as col4, b.col5
       coalesce(b.col5, bdef3.col5, bdef2.col5, bdef.col5) as col5
from tablea a left join
     tableb b
     on b.col2 = a.col2 and b.col3 = a.col3 left join
     tableb bdef3
     on b.col2 = a.col2 and b.col3 = '*' left join
     tableb bdef2
     on b.col2 = '*' and b.col3 = a.col3 left join
     tableb bdef
     on b.col2 = '*' and b.col3 = '*';

如果您想保证某些匹配项,则可能需要一个where子句:

where (b.col2 is not null or bdef3.col2 is not null or bdef2.col2 is not null or bdef.col2 is not null)

我认为上面的方法更有效,但是您可以更简洁地表达为:

select a.*, b.col4, b.col5
from tablea a left join
     tableb b
     on (b.col2 = a.col2 or b.col2 = '*') and
        (b.col3 = a.col3 or b.col3 = '*')
qualify 1 = row_number() over (partition by a.id order by (case when b.col2 = '*' then 2 else 1 end), (case when b.col3 = '*' then 2, else 1 end))