左外表连接多个条件。

时间:2018-04-27 00:18:29

标签: sql sql-server

我有两张桌子,想要离开外连接。

第一张表

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

SecondTable

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应该被添加到第一个。

我一直试图解决这个问题很长一段时间。有人可以帮我这个。谢谢。

我添加了斜体/星星以显示哪些数据已更新/添加

3 个答案:

答案 0 :(得分:0)

Basic Left Join theory

COALESCE function

SELECT a.ID, a.RenewalTerm, COALESCE( b.EffectiveDt, a.EffectiveDt ) AS EffectiveDt,
    COALESCE( b.RenewalDt, a.RenewalDt ) AS RenewalDt,
    MaxSize, AY, [DateTime]
FROM [FristTable] AS a
    LEFT JOIN [SecondTable] AS b ON a.ID = b.ID AND a.RenewalTerm = b.RenewalTerm

答案 1 :(得分:0)

看起来简单的left join + coalesce可以解决您的问题。 请检查this小提琴:

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

答案 2 :(得分:0)

我认为这是:

select t1.*, t2.DateTime, t2.AY, t2.MaxSize
from table1 t1 left join
     table2 t2
     on t1.id = t2.id and t1.renewalterm = t2.renewalterm;

也许我错过了什么,但我认为不需要coalesce()