我有一个select语句,我需要将其转换为Update语句。
SELECT GUID,seq original_seq_no, ROW_NUMBER()
OVER ( PARTITION BY GUID ORDER BY seq) AS new_seq_no
FROM CHK_SEQ;
上面的查询实际上是什么,假设我有一个具有唯一GUID的多个记录,并且表CHK_SEQ中列SEQ的值是6,9,10。然后运行上面的查询将SEQ的值更改为1,2,3,即new_seq_no。
任何人都可以帮助我。
感谢。
答案 0 :(得分:1)
试试这个(Sql-Server 2005及以上版本):
With cte as (
Select GUID,seq, row_number() over ( partition by GUID order by seq) AS new_seq_no
From CHK_SEQ
)
Update c
Set c.seq = new_seq_no
From CHK_SEQ c
Join cte on c.Guid = cte.Guid and c.seq = cte.seq;
答案 1 :(得分:0)
试试这个,
with cte
AS
(
SELECT GUID,seq original_seq_no, ROW_NUMBER()
OVER ( PARTITION BY GUID ORDER BY seq) AS new_seq_no
FROM CHK_SEQ
)
update CHK_SEQ
set CHK_SEQ.seq = r.new_seq_no
from cte r
where CHK_SEQ.seq = r.original_seq_no AND CHK_SEQ.GUID= r.GUID;
答案 2 :(得分:0)
merge into CHK_SEQ
using
SELECT rowid as rid,
ROW_NUMBER() OVER (PARTITION BY GUID ORDER BY seq) AS new_seq_no
FROM CHK_SEQ
) t on (chk_seq.rowid = t.rid)
when matched then update
set seq = new_seq_no;