Finding and removing duplicate column values in a SQL Server row

风格不统一 提交于 2020-01-05 07:24:14

问题


Yes, another SQL duplicates question :)

I have a SQL Server 2008 R2 table with multiple phone number columns, looking something like:

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

I'd like to remove the duplicate phone numbers from each row - for example, in row ID 2, I need to NULL Tel3 and Tel4, and in row 3 I need to NULL Tel4. I don't need to check for duplicates between rows - the same phone number can exist between in multiple rows, just not in different columns in the same row.

Can anyone suggest the best way to get rid of these duplicates?


回答1:


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



回答2:


You can find them using 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



回答3:


One possible way is to update it like this:

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

and then do the same update (with fewer comparisons in the where clause) to the other columns (except the first one).



来源:https://stackoverflow.com/questions/11737765/finding-and-removing-duplicate-column-values-in-a-sql-server-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!