如何使用另一个 table 中的多个值更新临时 table 中的多行,仅使用它们之间共有的一个 ID?

How to update multiple rows in a temp table with multiple values from another table using only one ID common between them?

我正在尝试协调来自另一个数据库 table(底部)的临时 table(顶部)中的 ID。由于我只有一个 ID 在两者之间是通用的,因此我只在我的临时 table 中获得所有行 (ReconGlobalRemunerationGrantID) 的最高结果。我的目标是获取每个唯一 ID 并更新我的温度 table。

现在,我的更新查询很简单,我使用 2 table 之间的公共 ID 进行更新。是否有函数或其他命令语句可用于获得预期结果?

update tgrg set ReconGlobalRemunerationGrantID = grg.GlobalRemunerationGrantID from @GlobalRemunerationGrant tgrg
join @GlobalRemuneration tgr on tgr.GlobalRemunerationID = tgrg.GlobalRemunerationID
join DataCore..GlobalRemuneration gr on gr.CompanyID = @CompanyID and gr.FiscalYearID = tgr.FiscalYearID and gr.DirectorDetailID = tgr.DirectorDetailID and tgr.GlobalRoleIDCODE = gr.GlobalRoleID
join DataCore..GlobalRemunerationGrant grg on gr.GlobalRemunerationID = grg.GlobalRemunerationID

谢谢。

根据评论 - 您有 2 个值可以匹配,而不仅仅是一个?例如,GlobalRemunerationID 和 GlobalRemunerationGrantID?

这是一个使用表 'temptable' 和 't1'

的示例
UPDATE temptable
SET    ReconGlobalRemunerationGrantID = t1.GlobalRemunerationGrantID
FROM   temptable
       INNER JOIN t1 ON temptable.GlobalRemunerationID = t1.GlobalRemunerationID
                    AND temptable.GlobalRemunerationGrantID = t1.GlobalRemunerationGrantID

更新如下

下面的版本取了两个数据集

  • 按 GlobalRemunerationID 对它们进行分区并按 ReconGlobalRemunerationGrantID 对它们进行排序以获得 'row numbers' (rn)
  • 在 GlobalRemunerationID 和 rn 上加入他们,让他们井井有条

关键代码如下(表格与您的完整数据集略有不同,抱歉 - 匹配您提供的数据集)。


; WITH tgrg AS
        (SELECT  GlobalRemunerationID, ReconGlobalRemunerationGrantID, 
                 ROW_NUMBER() OVER (PARTITION BY GlobalRemunerationID ORDER BY GlobalRemunerationGrantID) AS rn
            FROM #GlobalRemunerationGrant
        )
    UPDATE  tgrg 
    SET     ReconGlobalRemunerationGrantID = tgr.GlobalRemunerationGrantID 
    FROM    tgrg
            INNER JOIN 
               (SELECT   GlobalRemunerationID, GlobalRemunerationGrantID, 
                         ROW_NUMBER() OVER (PARTITION BY GlobalRemunerationID ORDER BY GlobalRemunerationGrantID) AS rn
                    FROM GlobalRemuneration
                ) AS tgr ON tgrg.GlobalRemunerationID = tgr.GlobalRemunerationID AND tgrg.rn = tgr.rn 

那里有完整的 db<>fiddle - 请注意,我更改了一些 ID 以证明它不是;没有使用它们来匹配。