3

我有一个带有列的表(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

4 回答 4

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
于 2011-09-17T17:14:49.713 回答
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;
于 2011-09-17T16:08:34.270 回答
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
于 2011-09-17T16:17:11.677 回答
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
于 2011-09-17T16:44:27.030 回答