4

我想更新row_number列 ( p_id) 为 1 的行数据,但此语法提供错误:

update app1 
set p_id = 1 
where Row_Number() = 1 over(p_id) 
4

3 回答 3

7

您不能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可以应用)

于 2011-04-16T11:59:09.290 回答
1

这将仅更新该年龄的第一位员工。可用作彩票类型逻辑

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
于 2011-04-16T12:25:07.577 回答
0

删除重复项 ;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

于 2015-12-03T17:48:01.670 回答