当前位置: 代码迷 >> Sql Server >> 求一sql查重复的语句,小弟我觉得有点难度哈
  详细解决方案

求一sql查重复的语句,小弟我觉得有点难度哈

热度:48   发布时间:2016-04-27 17:50:15.0
求一sql查重复的语句,我觉得有点难度哈
表有id,name,tel,add,web,email字段

表中ID是自增的,name与有重复的,但是没有完全重复的记录
比如有如下数据:
id           name           tel           add           web                                   email
1             张三           11111       西安         google.com                   [email protected]
2             李四           22222       北京         null                               null
3             王二麻子   11111       上海         baidu.com                     [email protected]
4             张三           33333       广州         null                               [email protected]
5             李四           22222       北京         sohu.com                 [email protected]                          

6             王二麻子     22222     北京         csdn.net                       [email protected]
..........
28000

现在要找出name相同   但是web长度最大(呵呵,NULL肯定是最小的啦,当然数据有2万条左右哈,web有的有,有的没有,有的2条相同,有的长度不同,但是name是相同的)   的记录,怎么搞啊   不会写

----------------------------------------------
上面只是举了个例子,实际的数据有9万条,重复的是28000条(都是重复2条,我用group   by   name   having   count(name)   筛选出来的,当前是要剔除重复,而且要保留web内容最多的一条记录..    

描述有点复杂,但是要求结果就剔除重复   而且web保留最大的


------解决方案--------------------
try

Select
A.*
From
TableName A
Inner Join
(
Select
name,
Max(Len(web)) As Len_web
From
TableName
Group By name
) B
On A.name = B.name And Len(A.web) = B.Len_web
------解决方案--------------------
declare @t table(id int,name varchar(20),tel varchar(10),addr varchar(50),web varchar(20),email varchar(50))
insert @t select 1, '张三 ', '11111 ', '西安 ', 'google.com ', ' [email protected] '
union all select 2, '李四 ', '22222 ', '北京 ',null,null
union all select 3, '王二麻子 ', '11111 ', '上海 ', ' baidu.com ', '[email protected] '
union all select 4, '张三 ', '33333 ', '广州 ',null, '[email protected] '
union all select 5, '李四 ', '22222 ', '北京 ', 'sohu.com ', '[email protected] '
union all select 6, '王二麻子 ', '22222 ', '北京 ', ' csdn.net ', '[email protected] '

select * from @t a where id=(select top 1 id from @t where name=a.name order by len(web) desc)
--结果
id name tel addr web email
  相关解决方案