sql显示另一个表中缺少重复的行

时间:2014-04-30 18:19:50

标签: sql sql-server-2008

在sql server中基本上我有查询在一个表中查找重复项。我想将此列表过滤到显示在一个表中的所有重复项,并且不包含在第二个表中

获得重复:

select   [OBId], COUNT(*) AS dupes  
FROM         [Broker] b
  GROUP BY [OBId]  
  HAVING      (COUNT(*) > 1)

经纪人有id,OBId

我想要在这个表中没有brokerid的所有重复项 第二张桌子 test

我试图做一个子查询,但我无法弄清楚

3 个答案:

答案 0 :(得分:0)

您可以使用子查询中的NOT EXISTS来执行此操作:

SELECT sub.*
FROM 
    (SELECT [OBId]
        , COUNT(*) AS dupes  
    FROM [Broker] b
    GROUP BY [OBId]  
    HAVING COUNT(*) > 1) sub
WHERE NOT EXISTS
    (SELECT 1
    FROM SomeSecondTable sst
    WHERE sub.OBId = BrokerId);

如果您尝试从Broker表中返回重复项的完整记录集,并且您想要取消第二个表中不存在的记录,那么您可以使用以下代码:

SELECT sub.*
FROM [Broker] b
WHERE EXISTS
    (SELECT [OBId]
        , COUNT(*) AS dupes  
    FROM [Broker] sb
    WHERE b.OBId = sb.OBId
    GROUP BY [OBId]
    HAVING COUNT(*) > 1)
AND NOT EXISTS
    (SELECT 1
    FROM SomeSecondTable sst
    WHERE b.OBId = BrokerId);

答案 1 :(得分:0)

您可以使用EXCEPT子句:

select   [OBId]
FROM     [Broker] b
  GROUP BY [OBId]  
  HAVING   (COUNT(*) > 1)

EXCEPT

select   [OBId]
FROM     [SecondTable] T2

答案 2 :(得分:0)

如果您只是使用子查询并说出

,该怎么办?
select [OBId], 
COUNT(*) AS dupes  
FROM [Broker] b
WHERE [OBId] NOT IN (select other_table_id from other_table)
GROUP BY [OBId]  
HAVING      (COUNT(*) > 1)