如下表所示:
rowId AccountId Organization1 Organization2
-----------------------------------------------
1 1 20 10
2 1 10 20
3 1 40 30
4 2 15 10
5 2 20 15
6 2 10 20
如何识别Organization1中特定帐户中不存在Organization2的记录
例如,在上面的给定数据中,我的结果将是一条记录,该记录将是AccountId 1,因为该特定帐户的organization1中不存在row3 organization2值30。
答案 0 :(得分:6)
SELECT rowId, AccountId, Organization1, Organization2
FROM yourTable yt
WHERE NOT EXISTS (SELECT 1 FROM yourTable yt2 WHERE yt.AccountId = yt2.AccountId AND yt.Organization1 = yt2.Organization2)
答案 1 :(得分:3)
您的问题有两种可能的解释。第一个(Organization1和Organization2列不相等)是微不足道的:
SELECT AccountID FROM Table WHERE Organization1 <> Organization2
但我怀疑你要求的解释稍微复杂一些(其中Organization2没有出现在同一账户的任何Organization1值中):
SELECT AccountID From Table T1 WHERE Organization2 NOT IN
(SELECT Organization1 FROM Table T2 WHERE T2.AccountID = T1.AccountID)
答案 2 :(得分:1)
以下是如何做到这一点:
测试数据:
CREATE TABLE #T(rowid int, acc int, org1 int, org2 int)
INSERT #T
SELECT 1,1,10,10 UNION
SELECT 2,1,20,20 UNION
SELECT 3,1,40,30 UNION
SELECT 4,2,10,10 UNION
SELECT 5,2,15,15 UNION
SELECT 6,2,20,20
然后执行自联接以发现丢失的org2:
SELECT
*
FROM #T T1
LEFT JOIN
#T T2
ON t1.org1 = t2.org2
AND t1.acc = t2.acc
WHERE t2.org1 IS NULL
答案 3 :(得分:0)
在Noel Abrahams出席时使用左连接。
答案 4 :(得分:0)
SELECT
*
FROM
[YorTable]
WHERE
[Organization1] <> [Organization2] -- The '<>' is read "Does Not Equal".