[英]Update a column with sequence number from 1 with a where and order by clauses
我正在尝试执行以下SQL查询来更新名为seq
的列,该列具有针对特定ID的编号顺序,但会引发错误:
关键字“ ORDER”附近的语法不正确。
DECLARE @id INT
SET @id = 0
UPDATE T_TRNHIST
SET @id = seq = @id + 1
WHERE Acc='12344'
OPTION ( MAXDOP 1 )
ORDER BY Recid, trnDate
我哪里出问题了?
您不能在更新语句中使用order by
,并且在使用古怪的更新时应该非常小心,因为它们非常不可预测。
一个简单,可信赖的解决方案是使用带有row_number
的可更新公用表表达式:
WITH CTE AS
(
SELECT seq,
ROW_NUMBER() OVER(ORDER BY Recid, trnDate) As rn
FROM T_TRNHIST
)
UPDATE CTE
SET seq = rn
您可以尝试UPDATE ... FROM ...
语法,该语法允许使用JOIN
。 以下是代码段以及测试数据:
declare @tbl table (seq int, Acc varchar(10), RecId int, trnDate date);
insert into @tbl values
(null, '12344', 2, '2019-05-05'),
(null, '12344', 1, '2019-05-06'),
(null, '12344', 5, '2019-05-04'),
(null, '12344', 5, '2019-05-03'),
(null, '12355', 1, '2019-05-05');
select * from @tbl
update t1 set t1.seq = t2.rn
from @tbl t1 join (
select row_number() over (order by RecId, trnDate) rn,
trnDate,
RecId,
Acc
from @tbl
where Acc = '12344'
) t2 on t1.trnDate = t2.trnDate and t1.RecId = t2.RecId and t1.Acc = t2.Acc
select * from @tbl
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.