查找和删除SQL Server行中的重复列值 [英] Finding and removing duplicate column values in a SQL Server row

查看:128
本文介绍了查找和删除SQL Server行中的重复列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是的,另一个SQL重复的问题:)

Yes, another SQL duplicates question :)

我有一个SQL Server 2008 R2表与多个电话号码列,看起来像:

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

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

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?

推荐答案

Sql Fiddle这里

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

这篇关于查找和删除SQL Server行中的重复列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆