[英]SQL query to delete records when the difference between two dates is greater than a certain value
[英]SQL Delete Duplicates with greater difference between two columns
我有一張類似於的桌子:
ID Value1 Value2
122 800 1600
122 800 1800
133 700 1500
154 800 1800
133 700 1500
188 700 1400
176 900 1500
從這個表我想刪除重復項( ID
為122
和133
),它們在value2和value1之間有較大的差異。
這意味着ID
為122
我想保留第一行( 1800-800>1600-800
)這意味着ID
為133
我想保留其中一個,因為它們都有相同的差異。
ID Value1 Value2
122 800 1600
122 800 1800 <------delete this row
133 700 1500 <------delete either this row or the other identical row
154 800 1800
133 700 1500 <------delete either this row or the other identical row
188 700 1400
176 900 1500
它的規模要大得多,所以我不能單獨刪除記錄。
有沒有辦法寫一個語句,將刪除我的表中的所有重復項,其中Value2 - Value1
大於Value2 - Value1
的重復?
SQL Server具有可更新CTE和子查詢的這一強大功能。 所以,你可以這樣做:
with todelete as (
select t.*,
row_number() over (partition by id order by value2 - value1) as diff_seqnum
from table t
)
delete from todelete
where diff_seqnum > 1;
也就是說,根據兩個值的差異枚舉每個id的行。 然后,只保留序列號為1
的行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.