更新具有重复项的列

Update a column that has duplicates

我正在使用 SQL 服务器 2008R2 并有一个名为 AirNewformat 的 table。这个 table 主要由 ID 列搜索,该列有很多重复项.我想通过添加一个名为 processed 的列来更新相同的 table,其中 ID 的第一个值在 processed 列中更新为 'N',其余重复项在 'D' 中更新为 'D'处理过的列。目前,我已将所有记录更新为 ND,但我希望看到如下例所示的更新。非常感谢任何帮助。

ID       Processed
---       ---------
12       N
12       D
12       D
13       N
13       D
13       D

如果可以,请尝试此代码(SQL Fiddle 为此: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, '') = '';

你可以试试这个:

;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;