在SQL Server中查找和删除重复的朋友连接

时间:2013-02-01 15:51:55

标签: sql sql-server sql-server-2008 tsql

我需要一个脚本才能找到不止一次拥有朋友关系的会员,因此它不会在网站上多次展示他们的友谊。

MemberConnection表如下:

+----------------------+------------+----------------+
|  MemberConnectionID  |  MemberID  |  ConnMemberID  |
+----------------------+------------+----------------+
|  25                  |  33        | 43             |
|  26                  |  43        | 33             |
|  27                  |  13        | 143            |
|  28                  |  143       | 13             |
|  29                  |  33        | 43             |
+----------------------+------------+----------------+

正如您所看到的,第25行和第29行是相同的,我需要找到这些重复项,以便删除它们。

如何为此编写脚本?

任何人都可以提供的帮助将不胜感激。

非常感谢提前

neojakey

4 个答案:

答案 0 :(得分:3)

如果您想留下一个连接,请尝试此操作:

使用此选项连接:

;WITH CTE
AS
(
   SELECT
      MemberConnectionID, 
      ROW_NUMBER() OVER (PARTITION BY MemberID, ConnMemberID ORDER BY MemberConnectionID) RN
   FROM MemberConnection 
)
SELECT 
      MemberConnectionID
FROM CTE
WHERE RN > 1

或使用它从表中删除:

;WITH CTE
AS
(
   SELECT
      ROW_NUMBER() OVER (PARTITION BY MemberID, ConnMemberID ORDER BY MemberConnectionID) RN
   FROM MemberConnection 
)
DELETE
FROM CTE
WHERE RN > 1

答案 1 :(得分:0)

您可以执行以下操作:

SELECT * FROM 
(SELECT MemberID,ConnMemberID  ,count( MemberID,ConnMemberID ) as c FROM MemberConnection group by MemberID,ConnMemberID ) x 
WHERE x.c >1

这将显示所有重复的行。

答案 2 :(得分:0)

将此作为测试:

DECLARE @Table AS TABLE
    (
      MemberConnectionID INT ,
      MemberID INT ,
      ConMemberID INT
    )

INSERT  INTO @Table
        SELECT  1 ,
                2 ,
                3
INSERT  INTO @Table
        SELECT  2 ,
                3 ,
                4
INSERT  INTO @Table
        SELECT  3 ,
                2 ,
                3

选择成员连接的出现次数

SELECT    COUNT(MemberConnectionID) AS Occurence ,
          MemberID ,
          ConMemberID
FROM      @Table
GROUP BY  MemberID ,
          ConMemberID

删除声明

DELETE  FROM @Table
FROM    @Table t
        INNER JOIN ( SELECT MemberID ,
                            ConMemberID
                     FROM   ( SELECT    COUNT(MemberConnectionID) AS Occurence ,
                                        MemberID ,
                                        ConMemberID
                              FROM      @Table
                              GROUP BY  MemberID ,
                                        ConMemberID
                            ) t2
                     WHERE  t2.Occurence > 1
                   ) t3 ON t3.MemberID = T.MemberID
                           AND t3.ConMemberID = t.ConMemberID

答案 3 :(得分:0)

我总是使用这个小查询(改为满足你的表格)。

Delete MemberConnection
from MemberConnection
join
(select max(MemberConnectionId)as CountIt, MemberId, ConnMemberId
    from #MemberConnection
    group by MemberId, ConnMemberId
    having count(1) > 1
) as derived
on MemberConnection.MemberId = derived.MemberId
and MemberConnection.ConnMemberId = derived.ConnMemberId
and CountIt > MemberConnectionId