1

我在两个单独的服务器上有两个数据集。他们都提取一列信息。

我想构建一个报告,显示仅出现在其中一个数据集中的行的值。

从我读过的内容来看,我似乎想在 SQL 端这样做,而不是在报告端;我不知道该怎么做。

如果有人能阐明这是如何可能的,我将不胜感激。

4

3 回答 3

1

您可以使用该NOT EXISTS子句来获取两个表之间的差异。

SELECT
    Column
FROM
    DatabaseName.SchemaName.Table1
WHERE
    NOT EXISTS
    (
        SELECT
            Column
        FROM
            LinkedServerName.DatabaseName.SchemaName.Table2
        WHERE
            Table1.Column = Table2.Column --looks at equalities, and doesn't
                                          --include them because of the
                                          --NOT EXISTS clause
    )

这将显示 中Table1未出现的行Table2。您可以反转表名以查找Table2未出现在 中的行Table1

编辑:进行了编辑以显示链接服务器的情况。此外,如果您想同时查看两个表中未共享的所有行,您可以尝试如下所示。

SELECT
    Column, 'Table1' TableName
FROM
    DatabaseName.SchemaName.Table1
WHERE
    NOT EXISTS
    (
        SELECT
            Column
        FROM
            LinkedServerName.DatabaseName.SchemaName.Table2
        WHERE
            Table1.Column = Table2.Column --looks at equalities, and doesn't
                                          --include them because of the
                                          --NOT EXISTS clause
    )

UNION

SELECT
    Column, 'Table2' TableName
FROM
    LinkedServerName.DatabaseName.SchemaName.Table2
WHERE
    NOT EXISTS
    (
        SELECT
            Column
        FROM
            DatabaseName.SchemaName.Table1
        WHERE
            Table1.Column = Table2.Column
    )
于 2012-07-13T15:21:48.523 回答
1

您还可以使用左连接:

select a.* from tableA a
    left join tableB b
    on a.PrimaryKey = b.ForeignKey
where b.ForeignKey is null

此查询将返回 tableA 中在 tableB 中没有相应记录的所有记录。

于 2012-07-13T15:38:18.917 回答
1

如果您希望行恰好出现在一个数据集中,并且每个表上都有一个匹配的键,那么您可以使用完全外连接:

select *
from table1 t1 full outer join
     table2 t2
     on t1.key = t2.key
where t1.key is null and t2.key is not null or
      t1.key is not null and t2.key is null

where 条件选择恰好匹配的行。

但是,此查询的问题是您会得到很多带有空值的列。解决此问题的一种方法是在 SELECT 子句中逐列遍历。

select coalesce(t1.key, t2.key) as key, . . . 

解决这个问题的另一种方法是使用带有窗口函数的联合。此版本汇集了所有行并计算该键出现的次数:

select t.*
from (select t.*, count(*) over (partition by key) as keycnt
      from ((select 'Table1' as which, t.*
             from table1 t
            ) union all
            (select 'Table2' as which, t.*
             from table2 t
            )
           ) t
     ) t
where keycnt = 1

这具有指定值来自哪个表的附加列。它还有一个额外的列 keycnt,值为 1。如果您有一个复合键,您只需替换为指定两个表之间匹配的列列表。

于 2012-07-13T16:00:42.383 回答