2012-07-31 95 views
1

,这是另一个SQL复制问题:)查找,并在SQL Server行删除重复列值

我有多个phone number列的SQL Server 2008 R2的表,看起来像:

ID Tel1 Tel2 Tel3 Tel4 Tel5 Tel6 
1 123 456 789 NULL NULL NULL 
2 123 456 123 123 NULL NULL 
3 456 789 123 456 NULL NULL 

我想从每一行中删除重复的电话号码 - 例如,在行ID 2中,我需要NULL Tel3和Tel4,并在行3我需要NULL Tel4。我不需要检查行之间的重复项 - 多行之间可以存在相同的电话号码,而不是同一行中的不同列中。

任何人都可以提出摆脱这些重复的最好方法吗?

回答

2

Sql Fiddle here

update PhoneNumbers 
    set Tel2 = case when Tel1 = Tel2 
        then null 
        else Tel2 end, 
     Tel3 = case when Tel3 in (Tel1, Tel2) 
        then null 
        else Tel3 end, 
     Tel4 = case when Tel4 in (Tel1, Tel2, Tel3) 
        then null 
        else Tel4 end, 
     Tel5 = case when Tel5 in (Tel1, Tel2, Tel3, Tel4) 
        then null 
        else Tel5 end, 
     Tel6 = case when Tel6 in (Tel1, Tel2, Tel3, Tel4, Tel5) 
        then null 
        else Tel6 end 
+0

可爱的,完美的作品 - 谢谢! – KenD 2012-07-31 12:08:34

+0

@KennyAnderson不客气:-) – 2012-07-31 12:08:56

+0

@NikolaMarkovinović+1虽然没有做到一步到位,不错! :) – 2012-07-31 12:13:01

1

可以使用UNPIVOT找到他们......

select id, telNo 
from phonenumbertable 
unpivot 
(telNo for tel in (tel1, tel2, tel3, tel4,tel5, tel6)) as u  
group by id,telno 
having COUNT(telno)>1 
+0

好的,这可以帮助我找到重复的东西,但是如何将它们清空? – KenD 2012-07-31 12:09:02

1

一种可能的方式是这样来更新它:

update tablename 
set Tel6 = null 
where Tel6 = Tel5 or Tel6 = Tel4 or Tel6 = Tel3 or Tel6 = Tel3 or Tel6 = Tel2 or Tel6 = Tel1 

,然后做同样的更新(与在那里比较少子句)到其他列(第一个除外)。