根据条件结果和多列从 table 中删除重复项
Remove duplicates from table based on conditional result and multiple columns
ID | OrgName | TaxID | IsActive
-------------------------------------------------------
1 | Miller | 111 | 1
1 | Miller | 111 | 1 -- Duplicate
1 | Miller | 111 | 0 -- Duplicate
1 | Miller | 111 | 0 -- Duplicate
2 | XYZ | 222 | 0
2 | XYZ | 222 | 0 -- Duplicate
我通过查找重复项得到这个结果,但在这里我想根据我的专栏结果删除。
我的首要任务是保留“IsActive”= 1 的记录,并删除其他记录,无论它是 1 还是 0。
但是如果没有“IsActive”= 1 的记录,则优先保留任何一个为 0 的记录。
结果将有两条记录 - 行 1 和 5.
感谢您的帮助!谢谢你!
对于您的示例数据,这可以满足您的要求:
select id, orgname, taxid, max(isactive) as isactive
from t
group by id, orgname, taxid;
使用cte
删除重复项并使用row_number
功能
insert @table (id,orgname,TaxID,IsActive)
select 1 , 'Miller' , 111 , 1 union all
select 1 , 'Miller' , 111 , 1 union all
select 1 , 'Miller' , 111 , 0 union all
select 1 , 'Miller' , 111 , 0 union all
select 2 , 'XYZ' , 222 , 0 union all
select 2 , 'XYZ' , 222 , 0
;
with cte as (
SELECT *, ROW_NUMBER() over (partition by id order by IsActive desc) rn from @table)
delete from cte where rn>1
select * from @table
ID | OrgName | TaxID | IsActive
-------------------------------------------------------
1 | Miller | 111 | 1
1 | Miller | 111 | 1 -- Duplicate
1 | Miller | 111 | 0 -- Duplicate
1 | Miller | 111 | 0 -- Duplicate
2 | XYZ | 222 | 0
2 | XYZ | 222 | 0 -- Duplicate
我通过查找重复项得到这个结果,但在这里我想根据我的专栏结果删除。
我的首要任务是保留“IsActive”= 1 的记录,并删除其他记录,无论它是 1 还是 0。
但是如果没有“IsActive”= 1 的记录,则优先保留任何一个为 0 的记录。 结果将有两条记录 - 行 1 和 5.
感谢您的帮助!谢谢你!
对于您的示例数据,这可以满足您的要求:
select id, orgname, taxid, max(isactive) as isactive
from t
group by id, orgname, taxid;
使用cte
删除重复项并使用row_number
功能
insert @table (id,orgname,TaxID,IsActive)
select 1 , 'Miller' , 111 , 1 union all
select 1 , 'Miller' , 111 , 1 union all
select 1 , 'Miller' , 111 , 0 union all
select 1 , 'Miller' , 111 , 0 union all
select 2 , 'XYZ' , 222 , 0 union all
select 2 , 'XYZ' , 222 , 0
;
with cte as (
SELECT *, ROW_NUMBER() over (partition by id order by IsActive desc) rn from @table)
delete from cte where rn>1
select * from @table