给出下表:
UserId | Idx
1 | 0
1 | 1
1 | 3
1 | 5
2 | 1
2 | 2
2 | 3
2 | 5
我想更新IDx列,该列已按UserId列正确分组:
UserId | Idx
1 | 0
1 | 1
1 | 2
1 | 3
2 | 0
2 | 1
2 | 2
2 | 3
我知道使用T-SQL(使用Cursor)是可行的,但是用一条语句也可以实现吗?
谢谢
答案 0 :(得分:2)
您可以使用 correlated 子查询:
update t
set idx = coalesce((select count(*)
from table as t1
where t1.userid = t.userid and t1.idx < t.idx
), 0
);
答案 1 :(得分:0)
使用ROW_NUMBER()进行分区
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
答案 2 :(得分:0)
使用可更新的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;
这应该是解决此问题的最快方法。