来自两个不同查询的两个结果集之间的罕见记录

时间:2014-02-05 15:48:46

标签: sql

我有两个查询(每个在不同的表上),并且有一个自己的where子句。
两个表的主键具有不同的名称但保持相同的值。
如何提取记录在结果集1中但在结果集2中没有。

以下是两个查询的示例
查询1:

SELECT DISTINCT [EntityID],[Year],[Name],[OperationalStatus],[RefTypeID] 
FROM [DB].[dbo].[Entity] 
WHERE [Year]='2014' AND [RefTypeID] IN ('abc','xys')

QUERY2:

SELECT DISTINCT [OrganizationID],[Year],[OperationalStatusID],[Active],[ModifiedBy],[ModifiedDate] 
      FROM [DB2].[dbo].[Organization] WHERE [Year]='2014'

query1的主键是[EntityID],第二个查询的主键是[OrganizationID]。这两列具有相同的值

1 个答案:

答案 0 :(得分:2)

像这样:

    SELECT * FROM
    (
    SELECT DISTINCT [EntityID],[Year],[Name],[OperationalStatus],[RefTypeID] 
    FROM [DB].[dbo].[Entity] A
    WHERE [Year]='2014' AND [RefTypeID] IN ('abc','xys') AND 
    Not Exists 
    (
      SELECT DISTINCT [OrganizationID],[Year],[OperationalStatusID],[Active],[ModifiedBy],     
      [ModifiedDate] 
      FROM [DB2].[dbo].[Organization] D WHERE [FiscalYear]='2014' AND
      A.EntityID = D.OrganizationID AND
      A.Year=D.Year
      A.Name = D. Name
    )
) AS T