更新顺序值

时间:2017-10-02 16:50:49

标签: tsql sql-update

我有一个带有ID和序列#(SEQ)起始编号的表。我想根据SEQ

更新每个ID的SQ编号

我这样的表

ID       SQ    SEQ
---      --    ---
100      0      11
100      0      11
100      0      11
200      0      13
200      0      13
200      0      13
200      0      13

我想得到这样的结果表:

ID     | SQ | SEQ

100      11      11
100      12      11
100      13      11
200      13      13
200      14      13
200      15      13
200      16      13

如何使用TSQL执行此操作?

2 个答案:

答案 0 :(得分:1)

试试这个

select id,(ROW_NUMBER() over(partition by id order by id) + seq - 1) as sqn,seq from @tbl

包含测试数据的完整示例代码

declare @tbl table(id int, sq int, seq int)
insert into @tbl
select 100,0,11 union all
select 100,0,11 union all
select 100,0,11 union all
select 200,0,13 union all
select 200,0,13 union all
select 200,0,13 union all
select 200,0,13 

select id,(ROW_NUMBER() over(partition by id order by id) + seq - 1) as sqn,seq from @tbl

结果

id  sqn seq
100 11  11
100 12  11
100 13  11
200 13  13
200 14  13
200 15  13
200 16  13

答案 1 :(得分:0)

试试吧。

SELECT 
ID,ROW_NUMBER() OVER(ORDER BY ID ) AS SQ,SEQ
FROM YOUR_TABLE

要进行更新,请使用它

 update a set sq = rn
    ID,ROW_NUMBER() OVER(ORDER BY ID ) AS rn,SEQ
    FROM YOUR_TABLE) as a