注册 登录
编程论坛 SQL Server论坛

sql 查询相同记录的语句

都督 发布于 2008-06-16 18:08, 3745 次点击
例如:
   一张表table1有2个字段,一个字段是id是自动标号,另一个是value值。
table 1
    id     value
    1        11
    2        22
    3        22
    4        11
怎么找出这个表中的相同记录。请大家帮忙,这是我上次面试的题目,明天复试。谢谢大家了。
8 回复
#2
都督2008-06-16 18:33
大家帮帮忙呀,我是用一个自我连接。
#3
都督2008-06-16 18:36
表里面有N条相同的记录,要查出来.

如:   
  ID         Name   
  12           d   
  34           e   
  543         t   
  34           e   
  12           d   
  45           y   
  543         t   
   
  查询的结果应为:   
  ID           Name   
  12           d   
  12           d   
  34           e   
  34           e   
  543         t   
  543         t


假如表名为Table03,可以用下面语句轻松实现:

select   id,name   from   table03   where   name   in(select   name   from     table03   group   by   name   having   count(name)>1)
#4
hgs502429352008-06-17 17:12
select name,count(id) as a from table group name having count(id)>1
#5
jxyga1112008-06-17 17:29
用rs.round>0时就提示
#6
provoke2008-06-18 18:49
[bo][un]hgs50242935[/un] 在 2008-6-17 17:12 的发言:[/bo]

select name,count(id) as a from table group name having count(id)>1



这种方法只适用于只有两个选择字段的查询,而且查询结果也不是楼主想要的,楼主的2个字段绝对是碰巧,或许还有其他字段没列出来而已。

可以考虑这样:
select * from  table1 where id in (select id from table1 group by id having count(id)>1)

只有id计数大于1的记录才返回
#7
bb38522008-06-19 10:18
好像用group by或者in会降低性能的,

select * from table1 t1
 where exists(select 1 from table1
              where (select count([value]) from table1 t2
                     where t2.[value]=t1.[value])>1)
#8
jxyga1112008-06-19 19:21
还没有解决啊
#9
都督2008-06-20 14:45
解决了
1