我想更新row_number
列 ( p_id
) 为 1 的行数据,但此语法提供错误:
update app1
set p_id = 1
where Row_Number() = 1 over(p_id)
我想更新row_number
列 ( p_id
) 为 1 的行数据,但此语法提供错误:
update app1
set p_id = 1
where Row_Number() = 1 over(p_id)
您不能ROW_NUMBER()
直接使用 - 您需要为此使用 CTE(通用表表达式):
;WITH DataToUpdate AS
(
SELECT
SomeID,
p_id,
ROW_NUMBER() OVER(ORDER BY .......) AS 'RowNum'
FROM
dbo.app1
)
UPDATE DataToUpdate
SET p_id = 1
WHERE
RowNum = 1
为了使用该ROW_NUMBER
函数,您还需要至少一个ORDER BY
子句来定义行排序的顺序。
从您的问题来看,尚不清楚您要按什么标准(列)来确定您ROW_NUMBER()
的 ,也不清楚有哪种列可以唯一标识一行(以便UPDATE
可以应用)
这将仅更新该年龄的第一位员工。可用作彩票类型逻辑
create table emp(name varchar(3),Age int, Salary int, IncentiveFlag bit)
insert into emp values('aaa',23,90000,0);
insert into emp values('bbb',22,50000,0);
insert into emp values('ccc',63,60000,0);
insert into emp values('ddd',53,50000,0);
insert into emp values('eee',23,80000,0);
insert into emp values('fff',53,50000,0);
insert into emp values('ggg',53,50000,0);
update A
set IncentiveFlag=1
from
(
Select row_number() over (partition by Age order by age ) AS SrNo,* from emp
)A
where A.SrNo=1
删除重复项 ;WITH CTE(Name,Address1,Phone,RN) AS (SELECT Name,Address1,Phone, ROW_NUMBER() OVER(PARTITION BY Name ORDER BY Name) AS RN) DELETE FROM CTE WHERE RN > 1