MSSQL:如何增加由另一列分组的int列?

MSSQL:如何增加由另一列分组的int列?,sql,sql-server,Sql,Sql Server,鉴于下表: UserId | Idx 1 | 0 1 | 1 1 | 3 1 | 5 2 | 1 2 | 2 2 | 3 2 | 5 我想更新Idx列,使其正确递增,并按用户ID列分组: UserId | Idx 1 | 0 1 | 1 1 | 2 1 | 3 2 | 0 2 | 1 2 | 2 2 | 3 我知道使用带有游标的T-S

鉴于下表:

UserId | Idx
1      | 0
1      | 1
1      | 3
1      | 5
2      | 1
2      | 2
2      | 3
2      | 5
我想更新Idx列,使其正确递增,并按用户ID列分组:

UserId | Idx
1      | 0
1      | 1
1      | 2
1      | 3
2      | 0
2      | 1
2      | 2
2      | 3
我知道使用带有游标的T-SQL是可能的,但是使用一条语句也可能吗

谢谢

您可以使用相关子查询:

update t
     set idx = coalesce((select count(*) 
                         from table as t1 
                         where t1.userid = t.userid and t1.idx < t.idx
                        ), 0
                       );
您可以使用相关子查询:

update t
     set idx = coalesce((select count(*) 
                         from table as t1 
                         where t1.userid = t.userid and t1.idx < t.idx
                        ), 0
                       );

将行号与分区一起使用

   update tablex set Idx=A.Idx
   from tablex T
   inner join 
   (
      select UserID ,ID,ROW_NUMBER() OVER (PARTITION BY UserID ORDER By UserID)-1 Idx
      from tablex       
   ) A on T.ID=A.ID

将行号与分区一起使用

   update tablex set Idx=A.Idx
   from tablex T
   inner join 
   (
      select UserID ,ID,ROW_NUMBER() OVER (PARTITION BY UserID ORDER By UserID)-1 Idx
      from tablex       
   ) A on T.ID=A.ID
使用可更新的CTE:

with toupdate as (
      select t.*,
             row_number() over (partition by user_id order by idx) - 1 as new_idx
      from t
     )
update toupdate
    set idx = new_idx
    where new_idx <> new_idx;
这应该是解决此问题的最快方法。

使用可更新的CTE:

with toupdate as (
      select t.*,
             row_number() over (partition by user_id order by idx) - 1 as new_idx
      from t
     )
update toupdate
    set idx = new_idx
    where new_idx <> new_idx;

这应该是解决此问题的最快方法。

光标是更新这些值的糟糕方法。Idx值是否重新排列以控制某种形式的表示顺序?如果是这样,通常不需要尝试消除存储表单中的间隙-您可以在选择过程中生成连续编号。光标是更新这些值的糟糕方式。Idx值是否会被重新排列以控制某种形式的表示顺序?如果是这样,通常不需要尝试消除存储表单中的间隙-您可以在选择过程中生成连续编号。@Powerslave。尽管逻辑是可行的,但这绝对不是SQL中的最佳方法Server@GordonLinoff. . . 我认为这是一次性的,因为更新不是每日运行的语句。所以,一两次就可以了。@Powerslave。尽管逻辑是可行的,但这绝对不是SQL中的最佳方法Server@GordonLinoff. . . 我认为这是一次性的,因为更新不是每日运行的语句。所以,一次或两次处决就可以了。