连接定义中的 Teradata 通配符
Teradata wildcard in join definition
我加入了如下表格:
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 可以是值 '*',它应该是通配符之类的东西,意思是,在这种情况下我们可以将 b.col2 的值连接到 a 的任何值上.col2 或值 b.col3 任何值 a.col3.
你能帮我定义一下吗?
听起来你有一个默认值。一种方法是多重比较:
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))
我加入了如下表格:
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 可以是值 '*',它应该是通配符之类的东西,意思是,在这种情况下我们可以将 b.col2 的值连接到 a 的任何值上.col2 或值 b.col3 任何值 a.col3.
你能帮我定义一下吗?
听起来你有一个默认值。一种方法是多重比较:
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))