sql - 多个条件下的左外表连接。
问题描述
我有两个表,想离开外连接。
第一个表
Id RenewalTerm EffectiveDt RenewalDt
400001 -1 8/1/2012 8/1/2013
400001 0 8/1/2013 8/1/2014
400001 1 8/1/2014 8/1/2015
400001 2 8/1/2015 8/1/2016
400001 3 8/1/2016 8/1/2017
400001 4 8/1/2017 8/1/2018
第二表
Id RenewalTerm MaxSize AY DateTime EffectiveDt RenewalDt
400001 -1 2 2013 2/25/2013 8/1/2012 8/1/2013
400001 -1 1.75 2013 2/25/2013 8/1/2012 8/1/2013
400001 2 1.75 2016 5/1/2016 8/1/2015 8/1/2016
预期的表格结果
Id RenewalTerm EffectiveDt RenewalDt DateTime AY MaxSize
400001 -1 8/1/2012 8/1/2013 *2/25/2013 2013 2*
*400001 -1 8/1/2012 8/1/2013 2/25/2013 2013 1.75*
400001 0 8/1/2013 8/1/2014 NULL NULL NULL
400001 1 8/1/2014 8/1/2015 NULL NULL NULL
*400001 2 8/1/2015 8/1/2016 5/1/2016 2016 1.75*
400001 3 8/1/2016 8/1/2017 NULL NULL NULL
400001 4 8/1/2017 8/1/2018 NULL NULL NULL
在第二个表中,更新期限 -1 重复,在第一个表中只有一个 -1。因此,应该使用 Maxsize、AY 和 datetime 更新 -1 中的一个,并且应该将第二个表中的新行 -1 添加到第一个表中。
在第二张表中,续订期限 2 仅为一次。因此,应该将第二个表中的额外列 Maxsize、AY 和 datetime 添加到第一个表中。
我一直在努力解决这个问题。有人可以帮我解决这个问题。谢谢你。
我添加了斜体/星号以显示哪些数据已更新/添加
解决方案
它看起来像一个简单的left join
+coalesce
解决您的问题。请检查这个小提琴:
Select
t1.Id,
t1.RenewalTerm,
coalesce(t2.EffectiveDt, t1.EffectiveDt) EffectiveDt,
coalesce(t2.RenewalDt, t1.RenewalDt) RenewalDt,
t2.DateTime,
t2.AY,
t2.MaxSize
From
table1 t1
left join table2 t2 on t1.id = t2.id and t1.RenewalTerm = t2.RenewalTerm