更新多个第二个ID以匹配系列的第一个ID

时间:2016-09-16 12:51:27

标签: sql sql-server sql-server-2008 tsql

这是我拥有的数据的子集:

|Id1|Id2|
---------
|100| 90|
|101| 90|
|102| 90|
|217|101|
|218|101|
|219|101|

但Id2应该匹配Id1每次单独出现的第一次出现,只要Id2发生变化,就像这样:

|Id1|Id2|
---------
|100|100|
|101|100|
|102|100|
|217|217|
|218|217|
|219|217|

如何使用更新语句在数千行中更改此内容?

感谢您的帮助,这很难解释!

1 个答案:

答案 0 :(得分:9)

您可以CTE使用FIRST_VALUE

;WITH ToUpdate AS (
   SELECT Id1, Id2,
          FIRST_VALUE(Id1) OVER (PARTITION BY Id2 ORDER BY Id1) AS newValue
   FROM mytable
)
UPDATE ToUpdate
SET Id2 = newValue

嗯,遗憾的是,FIRST_VALUE在SQL Server 2008中不可用。在这种情况下,您可以使用以下查询:

;WITH CTE_Rn AS (
   SELECT Id1, Id2,
          ROW_NUMBER() OVER (PARTITION BY Id2 ORDER BY Id1) AS rn
   FROM mytable
), ToUpdate AS (
   SELECT t1.Id1, t2.Id2, t2.Id1 AS newValue
   FROM mytable AS t1
   JOIN CTE_Rn AS t2 ON t1.Id2 = t2.Id2 AND t2.rn = 1
)
UPDATE ToUpdate
SET Id2 = newValue