日期:2014-05-17  浏览次数:20403 次

求一个在同一张表中查询出重复记录ID的方法
求一个在同一张表中查询出重复记录ID的语句,比如
表A中有重复数据
序号:1   姓名:AA   联系代码1:00001   联系代码2:null
序号:3   姓名:AA   联系代码1:00005   联系代码2:00001   
序号:5   姓名:AA   联系代码1:00001   联系代码2:00003  

求语句如何能查询出重复记录的序号3、5呢?
由于数据表中有几百万条数据,所以写法需要优点。感谢!

------解决方案--------------------
select 序号,姓名 from tb t where exists(
select 1 from tb where t.姓名=姓名
group by 姓名 having count(*)>1 and min(序号)<t.序号
)
------解决方案--------------------
--姓名重复的数据:
select a.*
  from tableName a
  where exists(select 1 from tablename b where b.姓名=a.姓名 and b.序号<>a.序号)

是否性能,需要结合索引来完成,如果序号作为主键的话,那么可以考虑在‘姓名’创建索引,
create nonclustered index ix_tablename_x1 on TableName(姓名)

改写查询语句:
select a.*
  from tableName a with(index(ix_tablename_x1))
  where exists(select 1 from tablename b where b.姓名=a.姓名 and b.序号<>a.序号)
------解决方案--------------------
--利用分组函数进行查询
1.select * from(select ROW_NUMBER() over(partition by 序号 order by 姓名) as a,* from table) as b
where a>1
--利用group by进行查询
2.SELECT 序号, 姓名, count(*)
FROM table
GROUP BY 序号, 姓名
HAVING count(*) > 1
- -话说你应该是应聘的面试题做不下去了吧,最近几个月这个问题都被问三四次了