SQL Update仅重复行

时间:2017-03-25 06:44:34

标签: sql sql-server

table_paysched

id |  ilno | acctno
1  |  1    | 001
2  |  1    | 001
3  |  2    | 001
4  |  1    | 002
5  |  1    | 002
6  |  0    | 003
7  |  1    | 003

我想将副本1s ilno更新为0.谢谢

通缉结果

id |  ilno | acctno
1  |  0    | 001
2  |  1    | 001
3  |  2    | 001
4  |  0    | 002
5  |  1    | 002
6  |  0    | 003
7  |  1    | 003

我正在使用SQL Server

2 个答案:

答案 0 :(得分:1)

您可以使用CTE与窗口函数row_number进行更新:

with cte as (
    select *, row_number() over (partition by acctno order by id desc) rn
    from t
    where ilno = 1
)
update cte
set ilno = 0
where rn <> 1;

Demo

答案 1 :(得分:0)

使用此

with temp as (
    select *, 
    row_number() over (partition by acctno order by id desc) row_num,
    count() over (partition by acctno ) cnt_num
    from myTable
)

update myTable m
set m.ilno = 0
where exists (select 1 from temp t where m.id = t.id and t.row_num = 1 and cnt_num > 1)