选择在同一表中的两列之间一对一匹配的行

时间:2019-01-23 16:43:19

标签: sql sql-server distinct

我有一个带有两种类型的ID列的SQL表。例如

ID_1    Name          Date     ID_2
 487     Joe    09/06/2004      332
 731    Mike    06/01/2004      116
 487     Joe    09/06/2004      354
 777    Rich    01/01/2002      455
 745    Mike    06/01/2004      116

有时ID_1具有多行,且ID_2的值不同。反之亦然,有时ID_2包含多行,且ID_1的值不同。

我想保留ID_1和ID_2一一对应的所有行。理想情况下,我还将用剩余的行制作另一个表,以便以后可以轻松查看它们。因此,在上面的示例中,只有一行(第四行)在ID_1和ID_2之间具有一对一的匹配:

ID_1    Name          Date     ID_2
 777    Rich    01/01/2002      455

所有其他行都有其中一个ID重复的行。因此,基本上是删除所有ID列都重复的行。

我尝试使用DISTINCT,但是保留了重复的行之一,而我希望将它们全部删除。

p.s。这不是关于联接表的问题-示例是单个表。

4 个答案:

答案 0 :(得分:1)

create table #one_to_one
(id_1 int, name varchar(20), dt date, id_2 int)

insert into #one_to_one values( 487,   'Joe',    '09/06/2004'  ,    332)
insert into #one_to_one values( 731,   'Mike',    '06/01/2004' ,     116)
insert into #one_to_one values(487,   'Joe',    '09/06/2004'  ,    354)
insert into #one_to_one values( 777,    'Rich',    '01/01/2002',      455)
insert into #one_to_one values( 745,    'Mike',    '06/01/2004',      116)


select id_1, name, dt, id_2
from (select *, count(*) over(partition by id_1) as id_1_count,
               count(*) over(partition by id_2) as id_2_count
      from #one_to_one) res
where id_1_count = 1 and id_2_count = 1;

答案 1 :(得分:0)

您可以使用窗口COUNT

CREATE TABLE only_one_to_one
AS
SELECT ID_1, Name, Date, ID_2
FROM (SELECT *,COUNT(*) OVER(PARTITION BY ID_1) AS ID1_cnt,
               COUNT(*) OVER(PARTITION BY ID_2) AS ID2_cnt
      FROM tab) sub
WHERE ID1_cnt = 1 AND ID2_cnt = 1;

db<>fiddle demo

答案 2 :(得分:0)

仅一对一

SELECT *
  FROM Table A
 WHERE (SELECT Count(1)
          FROM Table B
         WHERE A.ID_1 = B.ID_1) = 1
   AND (SELECT Count(1)
          FROM Table B
         WHERE A.ID_2 = B.ID_2) = 1

一个以上

SELECT *
  FROM Table A
 WHERE (SELECT Count(1)
          FROM Table B
         WHERE A.ID_1 = B.ID_1) > 1
    OR (SELECT Count(1)
          FROM Table B
         WHERE A.ID_2 = B.ID_2) > 1

答案 3 :(得分:0)

此代码将帮助您

create table #temp (ID_1 int,name varchar(255),[Date] date,ID_2 int)
insert into #temp values (487  ,  'Joe','09/06/2004', 332)
insert into #temp values (731  , 'Mike' ,  '06/01/2004'  ,    116   )
insert into #temp values (487  , ' Joe' ,  '09/06/2004'  ,    354   )
insert into #temp values (777  , 'Rich' ,  '01/01/2002'  ,    455   )
insert into #temp values (745  , 'Mike' ,  '06/01/2004'  ,    116   )


Select * from (
Select ROW_NUMBER() OVER(ORDER BY id_1 DESC)  AS Row#,ID_1,Name,Date,ID_2 
FROM #temp

) as T 

Where Row# = 4
Drop table #temp

enter image description here