表1销售额s
|国家 |状态|城市|销售_金额
表2目标 t
|国家 |状态|城市|目标_金额
需求:检查 t.City 是否为 NOT NULL,然后加入 t.City = s.city ;否则检查 t.State 是否为 NOT NULL,然后加入 t.State=s.State; ELSE 加入 t.Country=s.Country
SELECT * FROM Sales s
JOIN Target t
ON s.city = t.city (implement the above conditions here)
当 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