我有一个包含与此类似的数据的表
seq Controlid
1 12345
2 12345
5 12345
6 12345
9 12345
10 12345
11 12345
16 12345
1 451251
2 451251
3 451251
我正在寻找一种应用更新命令的方法,该命令可以为特定的Controlid重新排序seq列 - 所以在上述更新后给出Controlid 12345我最终会得到这样的数据:
seq Controlid
1 12345
2 12345
3 12345
4 12345
5 12345
6 12345
7 12345
8 12345
1 451251
2 451251
3 451251
seq columns数据类型为smallint 它始终从1开始。
(我正在使用SQL Server 2008 R2)
答案 0 :(得分:1)
试试这个
select
row_number() over (partition by Controlid order by seq) as seq, Controlid
from your_table
编辑:由于您无法使用视图,请尝试此更新
update t1
set
t1.seq=t2.seq_new from your_table as t1 inner join
(
select
row_number() over (partition by Controlid order by seq) as seq_new, seq,
Controlid
from your_table
) as t2 on t1.seq=t2.seq and t1.Controlid=t2.Controlid
答案 1 :(得分:0)
阅读Madhivanan的评论后,这应该适合你。
CREATE VIEW YOUR_VIEW_NAME
AS
SELECT O.rn,O.Controlid
from
(SELECT seq
,Controlid
,ROW_NUMBER() OVER(PARTITION BY Controlid order by Controlid ) as rn
FROM ORDER_SEQ) O