我正在使用SQL Server 2008R2,并且有一个名为AirNewformat
的表。这个表主要由ID
列搜索,该列有许多重复项。我想通过添加一个名为processed的列来更新同一个表,其中ID
的第一个值在处理列中更新为'N'
,其余的重复项在处理列中更新为'D'
。目前,我已将所有记录更新为N
或D
,但我希望看到如下例所示的更新。非常感谢任何帮助。
ID Processed
--- ---------
12 N
12 D
12 D
13 N
13 D
13 D
答案 0 :(得分:0)
请尝试使用此代码( SQL小提琴: http://sqlfiddle.com/#!3/03991/6 ):
将每个ID
组中的第一条记录更新为N
:
UPDATE
A
SET
A.Processed = 'N'
FROM
(
SELECT ID, Processed, ROW_NUMBER() OVER(ORDER BY ID) AS row_num FROM AirNewformat
) AS A
INNER JOIN
(
SELECT
C.ID,
MIN(C.row_num) AS min_row_num
FROM
(
SELECT ID, ROW_NUMBER() OVER(ORDER BY ID) AS row_num FROM AirNewformat
) AS C
GROUP BY C.ID
) AS B ON A.ID = B.ID AND A.row_num = B.min_row_num;
将所有其余记录更新为D
:
UPDATE
AirNewformat
SET
AirNewformat.Processed = 'D'
WHERE
ISNULL(AirNewformat.Processed, '') = '';
答案 1 :(得分:0)
你可以试试这个:
;with cte as
(
select ROW_NUMBER() over (PARTITION by ID order by ID) N, processed from airNewformat
)
update cte
set processed = case when N = 1 then 'N'
when N >1 then 'D' end;