左/右连接表与自身

时间:2017-04-06 09:25:53

标签: sql left-join rdbms

我有一个表格,其中包含每个月的所有活跃贷款(例如2017_01,2017_02,2017_03等)。由于我没有另外一张包含非活跃贷款(已关闭的贷款)的表格,我必须操纵同一张桌子才能获得每个特定月份的已结清贷款。

我尝试过RIGHT OUTER JOIN以获得前一个YEAR_MONTH的一部分贷款,并在下个月有一个NULL值,但由于该表使用LOAN_NUMBER字段作为键加入自身,我不是获得理想的结果。

知道我能做什么吗?

Ps:在其他情况下,我需要这样做,我使用了" WHERE NOT EXISTS"条款,但我有两个不同的表。

我的查询是:

SELECT DM07MD.LOAN_NUMBER, DM07MD2.LOAN_NUMBER AS L2
FROM [dbo].[DM_07MONTHLY_DATA] DM07MD
LEFT OUTER JOIN [dbo].[DM_07MONTHLY_DATA] DM07MD2
ON DM07MD.LOAN_NUMBER = DM07MD2.LOAN_NUMBER
AND DM07MD.YYYY_MM = '2017_01'

WHERE DM07MD.S90T01_CLIENT_SEGMENT IN ('PI', 'MICRO')
AND DM07MD.S90T01_IS_RESTRUCTURED = 1
AND DM07MD2.LOAN_NUMBER IS NULL
AND DM07MD.YYYY_MM = '2017_02'

1 个答案:

答案 0 :(得分:0)

您可以使用exists,

获得相同的效果
 SELECT DM07MD.LOAN_NUMBER FROM [dbo].[DM_07MONTHLY_DATA] DM07MD where  DM07MD.YYYY_MM = '2017_02' and not exists 
( SELECT 1 FROM [dbo].[DM_07MONTHLY_DATA] DM07MD2 where  DM07MD.YYYY_MM = '2017_01' and DM07MD.LOAN_NUMBER=DM07MD2.LOAN_NUMBER )