簡體   English   中英

如何在SQL Server中使用自連接將表中的現有列值替換為新列值?

[英]How to replace a existing column value with new column value in a table using self join in SQL Server?

我有以下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需要替換,而且會花費大量時間。

我認為這會根據您的規則為您提供最新的商家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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM