当前位置: 代码迷 >> Sql Server >> 高分求大神给一段代码,驱除数据库中重复的数据
  详细解决方案

高分求大神给一段代码,驱除数据库中重复的数据

热度:27   发布时间:2016-04-24 09:59:28.0
高分求大神给一段代码,清除数据库中重复的数据
MSSQL2008 数据库,约4G.

表user   
字段:id name pass email tel  other 

现在的问题是:name和tel 可能会有同时重复的。要做的就是:找出name,tel 同时重复的数据,
然后把重复的数据中的pass,email,other项的数据放到其中一个数据的other列中,然后删除其它列。

比如数据如下:
id     name    pass   email  tel  other
 8      小明    a     b    e     g
19    小明    Y          X        e         o
89    小明    M          N        e         P

这三顶的name,tel 都是一样,假设把其它数据放到ID最小的那个中去,那和就是把ID为19的Y,X,o 还有ID为89的M,N,P都方到
ID为8的那行中去,变成
id     name    pass   email  tel  other
 8      小明    a            b       e      gY,X,o,M,N,P

我只会ASP和SQL,目前安装的是SQL2008 ,其它的都不太会,请大神给段我可以操作的,看得懂的。

另外由于数据库较大4G,所以是是可以一步处理呢?增加效率,以免死机之类的?
谢谢。

other中的各项数据以,号分开。
------解决思路----------------------
打开查询分析器按F1,然后搜CTE  看看MSDN中的用法
------解决思路----------------------

--测试数据
with cte as 
(select 8 as id, '小明' as name, 'a' as pass,'b' as email,'e' as tel,'g' as other union all
select 19 as id, '小明' as name, 'Y' as pass,'x' as email,'e' as tel,'o' as other union all
select 89 as id, '小明' as name, 'M' as pass,'n' as email,'e' as tel,'p' as other),
--按照ID进行排序。并合并同一行需要合并的3列
cte1 as 
(select id,name,pass,email,tel,other,pass+','+email+','+other+'' as others,
ROW_NUMBER()over(PARTITION by name, tel order by id) as n from cte),
--利用一个XML 进行分组之后 字符串的连接。
cte2 as 
(select name,tel,(select ','+other from (select name,tel,
       pass+','+email+','+other as other from cte1
       where n!=1) as b where b.name=a.name and b.tel=a.tel for xml path('')) as other from cte1 as a
       where n=1
       group by name,tel)
       
        --得出结果。
select id,b.name,b.pass,b.email,b.tel,b.other+a.other from cte2 as a join cte1 as b 
on a.name=b.name and a.tel=b.tel and b.n=1
--看到就一个个的CTE 一次执行看看每个CTE的结果。就OK了


--执行结果
id          name pass email tel  
----------- ---- ---- ----- ---- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
8           小明   a    b     e    g,Y,x,o,M,n,p

(1 行受影响)

------解决思路----------------------
引用:
决定在表中现新增一个字段num
现在总字段变成id,name,password,other,num
num用来记录重复的数量

现在就是过滤PASSWORD项中复杂的 数据,并把重复数据中的other数据集合到ID最小的那条中,在该条num字段中记录重复数量。删除其它重复项,并保留ID最小的那条。

嘛烦大哥给出一段实际执行的代码,最好有个QQ号可以问一下。


QQ私信发你了,你把新的表结构贴出来。NUM是根据partition by name order by id来的吗?
感觉思路啥都没变啊。反而简单了一点。
  相关解决方案