我需要根据列的值识别重复行并更新" 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
列在原始数据集中找到重复集,并更新启动集合的行。
答案 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)
使用CTE
和ROW_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