我有以下TempTableA
Application Id Merchant
--------------------------------
201797838 331543 681
实际上,ID 331543不是商家681的正确ID。
所以我需要找到正确的ID,然后替换现有的Id。
手动我将执行以下操作以找到正确的ID:
首先,我将使用表格SchemeData中的现有Id 331543查询以下列,如下所示
1. SchemeName
2. TenureInMonths
3. ROI
4. Approved
5. IsSubvented
查询:
select SchemeName, TenureInMonths, ROI, Approved, IsSubvented
from SchemeData
where ID in (331543)
我将获得以下输出
SchemeName TenureInMonths ROI Approved IsSubvented
------------------------------------------------------------------
6 Mnths Vanilla 6 18 1 N
要查找正确的ID,我将查询如下:
select Id
from SchemeData
where SchemeName like '%6 Mnths Vanilla%'
and TenureInMonths = 6
and ROI = 18
and Approved = 1
and IsSubvented = 'N'
and Merchant = 681
and ID_EndDate >= GETDATE()
我将获得相应商家681的以下ID
Id
-------
317122
现在我将用正确的Id替换现有的Id,我的TempTableA将如下所示
Application Id Merchant
--------------------------------
201797838 317122 681
您能否帮助您使用SQL查询找到正确的ID,而不是每次都手动执行,因为有很多ID需要替换,并且需要花费大量时间。
答案 0 :(得分:0)
我认为这会根据您的规则为您提供最新的商家ID:
select s.*, s2.id as newid
from schemadata s cross apply
(select top 1 s2.*
from schemadata sd2
where s2.SchemeName like '%' + s2.SchemeName + '%' and
s2.TenureInMonths = s.TenureInMonths
s2.ROI = s.ROI and
s2.Approved = s.Approved and
s2.IsSubvented = s.IsSubvented
s2.Merchant = s.Merchant
s2.ID_EndDate >= GETDATE()
) s2;
如果是这样,您可以轻松地将其放入update
:
update s
set id = s2.id
from schemadata s cross apply
(select top 1 s2.*
from schemadata sd2
where s2.SchemeName like '%' + s2.SchemeName + '%' and
s2.TenureInMonths = s.TenureInMonths
s2.ROI = s.ROI and
s2.Approved = s.Approved and
s2.IsSubvented = s.IsSubvented
s2.Merchant = s.Merchant
s2.ID_EndDate >= GETDATE()
) s2;