加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sql – 显示所有重复的行

发布时间:2020-12-12 16:40:12 所属栏目:MsSql教程 来源:网络整理
导读:假设我有以下sql表 objid firstname lastname active 1 test test 0 2 test test 1 3 test1 test1 1 4 test2 test2 0 5 test2 test2 0 6 test3 test3 1 现在,我感兴趣的结果如下: objid firstname lastname active 1 test test 0 2 test test 1 4 test2 test
假设我有以下sql表
objid  firstname lastname active
     1       test      test     0
     2       test      test     1
     3       test1     test1    1
     4       test2     test2    0
     5       test2     test2    0
     6       test3     test3    1

现在,我感兴趣的结果如下:

objid  firstname lastname active
     1       test      test     0
     2       test      test     1
     4       test2     test2    0
     5       test2     test2    0

我该如何实现?
我已经尝试过以下查询,

select firstname,lastname from table
group by firstname,lastname
having count(*) > 1

但这个查询给出了结果

firstname  lastname
     test        test
     test2       test2

解决方法

您已经找到重复的记录,但是您有兴趣获取附加的所有信息.您需要将您的副本加入主表以获取该信息.
select *
  from my_table a
  join ( select firstname,lastname 
           from my_table 
          group by firstname,lastname 
         having count(*) > 1 ) b
    on a.firstname = b.firstname
   and a.lastname = b.lastname

这与内部连接相同,意味着对于您的子查询中的每个记录,找到重复记录,您可以从主表中找到具有相同firstseen和lastseen组合的所有内容.

您也可以在though you should test the difference中执行此操作:

select *
  from my_table a
 where ( firstname,lastname ) in   
       ( select firstname,lastname 
         having count(*) > 1 )

进一步阅读:

> A visual representation of joins从编码恐怖
> Join explanation维基百科

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读