如何查找重复行并更新序列中的第一行?

时间:2017-08-23 16:13:39

标签: sql-server tsql select

我需要根据列的值识别重复行并更新" leading"行。

例如,假设我有以下数据:

Code   Amount
----   ------
ABC     100
DEF     200
HIJ     300
HIJ     170
HIJ     130

使用SQL更新,数据集应如下所示:

Code   Amount
----   ------
ABC     100
DEF     200
HIJ     0 (this one is set to 0 based on row number)
HIJ     170
HIJ     130

因此,根据Code列在原始数据集中找到重复集,并更新启动集合的行。

2 个答案:

答案 0 :(得分:2)

假设你有b = np.array([[1,2], [2,3], [5,6], 7,8], [10,1]])使用序数:

a==b

rextester演示:http://rextester.com/PTQ30474

更新输出:

id
更新后的

表:

;with cte as (
  select *
      ,rn = row_number() over (partition by code order by id)
  from t
)
update cte
  set Amount = 0
output inserted.code, inserted.amount
from cte 
where rn = 1
  and exists (
    select 1
    from cte i
    where i.code=cte.code
      and i.rn > 1
  )

答案 1 :(得分:2)

使用CTEROW_NUMBER/COUNT窗口函数:

WITH cte AS (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY Code ORDER BY id) AS rn
         , COUNT(*)OVER (PARTITION BY Code) AS cnt
  FROM tx
  -- WHERE tx.Code IS NOT NULL
)
UPDATE cte
SET Amount = 0
WHERE rn = 1 AND cnt > 1;

<强> Rextester Demo

您需要按照id/timestamp

的顺序排序