JOIN 和 CASE WHEN - 如何检查 NULL 并使用该字段来连接 2 个表?

Dat*_*ng_ 1 sql join case

表格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
  • 否则检查 if t.State IS NOT NULL,然后加入t.State = s.State;
  • 否则加入t.Country = s.Country
SELECT * 
FROM Sales s
JOIN Target t ON s.city = t.city  (implement the above conditions here)
Run Code Online (Sandbox Code Playgroud)

当 LHS 或 RHS 恒定时,我已经在 J​​OIN 中完成了 CASE WHEN 。但在这种情况下,LHS 和 RHS 都会根据条件检查而改变,我不确定如何实现这一点。

top*_*ail 5

我认为你可以通过这种方式编写一个基于集合的解决方案(不要过于字面地考虑 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)