SQL比较表/完全外部联接,两侧均带有过滤器

时间:2019-11-25 20:47:11

标签: sql sql-server tsql outer-join

真实案例

我有一个表(在MS SQL Server中),该表具有以下列: AccountId,RunId和详细信息

我想比较2个“运行”,并找出运行之间的差异。

为简化起见,我制作了以下示例。

简化的案例

CREATE TABLE #T (
    AccountId INT NOT NULL,
    RunId INT NOT NULL
)

INSERT INTO #T
(AccountId , RunId)
VALUES
(1, 1),
(1, 2),
(2, 2),
(3, 1)
DROP TABLE #T

所需的输出(;分隔)

AccountId;Run1;Run2
2;NULL;2
3;1;NULL

到目前为止有效的解决方案

1:

SELECT COALESCE(T1.AccountId, T2.AccountId) [AccountId], T1.RunId [Run1], T2.RunId [Run2]
FROM #T T1
FULL OUTER JOIN #T T2 ON T2.AccountId = T1.AccountId AND T2.RunId = 2 AND T1.RunId = 1
WHERE (T1.RunId = 1 OR T1.RunId IS NULL)
AND (T2.RunId = 2 OR T2.RunId IS NULL)
AND (T1.AccountId IS NULL OR T2.AccountId IS NULL)
ORDER BY [AccountId]

2:

SELECT COALESCE(T1.AccountId, T2.AccountId) [AccountId], T1.RunId [Run1], T2.RunId [Run2]
FROM (SELECT TOP 1 0 [0]) AS [T0]
FULL OUTER JOIN #T T1 ON T1.RunId = 1
FULL OUTER JOIN #T T2 ON T2.AccountId = T1.AccountId AND T2.RunId = 2 AND [0] = 0
WHERE ([0] = 0 OR T2.RunId = 2)
AND (T1.AccountId IS NULL OR T2.AccountId IS NULL)
ORDER BY [AccountId]

3:

SELECT COALESCE(T1.AccountId, T2.AccountId) [AccountId], T1.RunId [Run1], T2.RunId [Run2]
FROM (
    SELECT * FROM #T WHERE #T.RunId = 1
) T1
FULL OUTER JOIN (
    SELECT * FROM #T WHERE #T.RunId = 2
) T2 ON T2.AccountId = T1.AccountId
WHERE (T1.AccountId IS NULL OR T2.AccountId IS NULL)

我的实际问题

所有三种解决方案都很难看。有没有更简单的方法?

如果不是,那么您认为三个最好的是哪个?

2 个答案:

答案 0 :(得分:1)

怎么样:

ProjectLinkToOMS_....

这只会向您显示一次运行中的帐户,以及它们所在的运行。

答案 1 :(得分:0)

我用于比较两个相同表的日常解决方案是:

-- t1 rows not in t2
select * from t1
except
select * from t2

-- t2 rows not in t1
select * from t2
except
select * from t1