删除没有前导零的行

时间:2011-09-17 16:01:16

标签: sql-server-2008 deduplication

我有一个带有列的表(registration_no varchar(9))。这是一个示例:

id  registration no
1   42400065
2   483877668
3   019000702
4   837478848
5   464657588
6   19000702
7   042400065

请注意注册号码如(042400065)和(42400065),它们几乎相同,差别只是前导零。

我想选择与上述情况相同的所有注册号,并删除不带前导零的注册号,即(42400065)

请注意,在我删除没有前导零的那些(42400065)之前,我需要确保有一个等价的前导零(042400065)

4 个答案:

答案 0 :(得分:2)

declare @T table
(
  id int,
  [registration no] varchar(9)
)

insert into @T values
(1,   '42400065'),
(2,   '483877668'),
(3,   '019000702'),
(4,   '837478848'),
(5,   '464657588'),
(6,   '19000702'),
(7,   '042400065')

;with C as
(
  select row_number() over(partition by cast([registration no] as int) 
                           order by [registration no]) as rn
  from @T
)
delete from C
where rn > 1

答案 1 :(得分:0)

create table temp id int;
insert into temp select id from your_table a where left (registration_no, ) = '0' and 
   exists select id from your_table 
              where a.registration_no = concat ('0', registration_no)

delete from your_table where id in (select id from temp);

drop table temp;

答案 2 :(得分:0)

我认为您可以使用单个DELETE语句执行此操作。 JOIN确保只删除重复项,并且约束通过不以“0”开头的注册号进一步限制它。

DELETE 
    r1
FROM
    Registration r1
JOIN
    Registration r2 ON RIGHT(r1.RegistrationNumber, 8) = r2.RegistrationNumber
WHERE
    LEFT(r1.RegistrationNumber, 1) <> '0'

运行上面的DELETE后,您的表格如下所示。我在SQL Server 2008实例上测试过它。

ID          RegistrationNumber
----------- ------------------
2           483877668
3           019000702
4           837478848
5           464657588
7           042400065

答案 3 :(得分:0)

此解决方案不依赖于特定长度的注册号,它只查找那些相同的整数,但不是相同的值(因为前导零)并选择具有'0'作为第一个角色。

DELETE r
FROM Registration AS r
JOIN Registration AS r1 ON r.RegistrationNo = CAST(r1.RegistrationNo AS INT)
    AND r.RegistrationNo <> r1.RegistrationNo
WHERE CHARINDEX('0',r.registrationno) = 1