根据条件加入不同

时间:2017-10-16 09:14:05

标签: sql-server join conditional-statements

我有一个加入,我想考虑'LASTAvenant.CodeAvenant'= 0的情况:

FROM Avenant BeforeLastAvenant
JOIN Avenant LASTAvenant ON LASTAvenant.CodeContrat =
BeforeLastAvenant.CodeContrat AND LASTAvenant.CodeAvenant > 0
                            AND LASTAvenant.CodeAvenant - 1 = BeforeLast.CodeAvenant

我使用此连接比较LASTAvenant和BeforeLastAvenant中的值,因此条件'> 0'有意义(避免-1之后)。

鉴于此,我将无法访问'CodeAvenant'= 0,但我想将其与历史表中的先前版本进行比较。 根据'CodeAvenant',我想加入历史表或LASTAvenant表。

我想做点什么:

JOIN Avenant LASTAvenant ON LASTAvenant.CodeContrat = 
BeforeLastAvenant.CodeContrat AND IF LASTAvenant.CodeAvenant = 0 
                                  THEN ( --here comes the tricky part I want to replace the 
--table
                                  'BeforeLastAvenant.CodeAvenant = HistorytableAvenant.CodeAvenant'
                                       )
                             ELSE  LASTAvenant.CodeAvenant =  BeforeLastAvenant.CodeAvenant      

我试图尽可能清楚。

2 个答案:

答案 0 :(得分:2)

如果我理解你的情况,这就是你想要的。试试这个

JOIN Avenant LASTAvenant ON LASTAvenant.CodeContrat = BeforeLastAvenant.CodeContrat
and BeforeLastAvenant.CodeAvenant = HistorytableAvenant.CodeAvenant
where LASTAvenant.CodeAvenant = 0 

union all

JOIN Avenant LASTAvenant ON LASTAvenant.CodeContrat = BeforeLastAvenant.CodeContrat
and LASTAvenant.CodeAvenant - 1 =  BeforeLastAvenant.CodeAvenant
where LASTAvenant.CodeAvenant <> 0 

答案 1 :(得分:1)

一个解决方案:使用UNION ALL,您可以使用CodeAvenant = 0作为CodeAvenant = -1记录添加历史记录:

FROM Avenant LASTAvenant
JOIN
(
  SELECT CodeContrat, CodeAvenant, <other columns>
  FROM Avenant
  UNION ALL
  SELECT CodeContrat, -1 AS CodeAvenant, <other columns>
  FROM HistorytableAvenant
  WHERE CodeAvenant = 0
) BeforeLastAvenant ON  BeforeLastAvenant.CodeContrat = LASTAvenant.CodeContrat
                    AND BeforeLastAvenant.CodeAvenant = LASTAvenant.CodeAvenant - 1;