使用组内的递增数字更新 table 行

Update table rows with incremental number within group

我需要更新一个 table 以便相同 'group' 的行(示例中的代码 + 颜色)在组内获得递增的数字。每组的行应编号为 1、2、3...

id   | Code | Color   |Required_New_field
--------------------------
1231 |001   |Red      | 1
1232 |001   |Red      | 2
1233 |002   |Red      | 1
1234 |001   |Red      | 3
1235 |001   |Blue     | 1
1236 |002   |Red      | 2
1237 |001   |Blue     | 2
1238 |002   |Blue     | 1
1239 |002   |Red      | 3
...

在代码=001 和颜色=红色的示例行中,应该分别得到 1、2、3。

我尝试了几种使用子查询和 'group by' 的方法,但我意识到这实际上不是正确的方法。

如有任何提示,我们将不胜感激!

已编辑: ROW_NUMBER() 答案很棒!遗憾的是,我必须 运行 它在旧的 sql_server 2000 版本上。并且 ROW_NUMBER() 在 2005 年及以上可用(有关可用性的详细信息 here)。还有其他选择吗?

您可以使用 row_number() 来计算数字:

select t.*,
       row_number() over (partition by code, color order by id) as required_new_field
from t;

要进行更新,请使用可更新的 CTE:

with toupdate as (
       select t.*,
              row_number() over (partition by code, color order by id) as seqnum
       from t
      )
update toupdate
    set required_new_field = seqnum;

虽然我同意大家的评论,ROW_NUMBER() 在 SQL Server 2005 中可用,但这里是使用 COUNT() 的子查询的替代解决方案。可以在 SQL Server 2000 上使用。请注意,就性能而言,它的成本要高得多:

SELECT 
    t2.*,
    (SELECT COUNT(*) 
     FROM your_table t1 
     WHERE t1.code = t2.code 
       AND t1.color = t2.color
       AND t1.id <= t2.id) AS Rn
FROM 
    your_table t2

编辑 - 更新:

UPDATE t2 
SET RN = (SELECT COUNT(*) 
          FROM your_table t1 
          WHERE t1.code = t2.code 
            AND t1.color = t2.color
            AND t1.id <= t2.id) 
FROM your_table t2