表格1 -Sales
| Country | State | City| Sales_Amt
Run Code Online (Sandbox Code Playgroud)
表 2 -Target
| Country | State | City| Target_Amt
Run Code Online (Sandbox Code Playgroud)
要求:
t.City IS NOT NULL,然后加入t.City = s.city;t.State IS NOT NULL,然后加入t.State = s.State;t.Country = s.CountrySELECT *
FROM Sales s
JOIN Target t ON s.city = t.city (implement the above conditions here)
Run Code Online (Sandbox Code Playgroud)
当 LHS 或 RHS 恒定时,我已经在 JOIN 中完成了 CASE WHEN 。但在这种情况下,LHS 和 RHS 都会根据条件检查而改变,我不确定如何实现这一点。
我认为你可以通过这种方式编写一个基于集合的解决方案(不要过于字面地考虑 if/else if/else 逻辑:
select *
from Sales s
inner join Target t
on s.City = t.City
union all
select *
from Sales s
inner join Target t
on s.State = t.State
where s.City is null
union all
select *
from Sales s
inner join Target t
on s.Country = t.Country
where
s.City is null
and s.State is null
Run Code Online (Sandbox Code Playgroud)