查看另一个表中是否存在多个条目

时间:2015-05-14 15:31:45

标签: sql-server tsql

数据集1:

Cust_Ref    |   ACC1    |    ACC2   |    ACC3
------------+-----------+-----------+---------
1000001     |   ALPHA   |   BRAVO   |   CHARLIE
1000002     |   ALPHA   |   BRAVO   |   CHARLIE
1000003     |   ALPHA   |   BRAVO   |   CHARLIE
1000004     |   DELTA   |   ECHO    |   
1000005     |   DELTA   |   ECHO    |   
1000006     |   FOXTROT | 
1000007     |   FOXTROT |

数据集2:

Cust_Ref    |   ACC
------------+--------
1000001     |   ALPHA
1000001     |   BRAVO
1000001     |   DELTA
1000004     |   DELTA
1000004     |   ECHO
1000006     |   FOXTROT

数据集1显示客户参考及其应具有的帐户。所以例如1000001必须有帐户 - ALPHA,BRAVO,CHARLIE。客户1000002有DELTA和ECHO等

数据集2显示了与客户参考实际关联的帐户。

我可以在哪里使用T-SQL返回缺少帐户的实例吗?

实施例: 在我提供的数据集中,客户1000001应该有ALPHA,BRAVO,CHARLIE,但数据集2显示客户没有CHARLIE。

3 个答案:

答案 0 :(得分:3)

考虑此DDL和样本数据:

DECLARE @Table1 TABLE (
    Cust_Ref VARCHAR(10) PRIMARY KEY,
    ACC1 VARCHAR(10) NULL,
    ACC2 VARCHAR(10) NULL,
    ACC3 VARCHAR(10) NULL
)

INSERT INTO @Table1 VALUES
('1000001','ALPHA','BRAVO','CHARLIE'),
('1000002','ALPHA','BRAVO','CHARLIE'),
('1000003','ALPHA','BRAVO','CHARLIE'),
('1000004','DELTA','ECHO',NULL),
('1000005','DELTA','ECHO',NULL),
('1000006','FOXTROT','FOXTROT',NULL),
('1000007','FOXTROT','FOXTROT',NULL)

DECLARE @Table2 TABLE (
    Cust_Ref VARCHAR(10) NOT NULL,
    ACC VARCHAR(10) NOT NULL
)

INSERT INTO @Table2 VALUES
('1000001','ALPHA'),
('1000001','BRAVO'),
('1000001','DELTA'),
('1000004','DELTA'),
('1000004','ECHO'),
('1000006','FOXTROT')

你可以这样使用UNPIVOT和EXCEPT:

SELECT Cust_Ref, ACC
FROM @Table1 UNPIVOT (ACC FOR COL IN (ACC1, ACC2, ACC3)) U
EXCEPT
SELECT Cust_Ref, ACC
FROM @Table2

答案 1 :(得分:1)

(Select cust_ref, acc1 account
from dataSet1
union
Select cust_ref, acc2 account
from dataSet1
union
Select cust_ref, acc3 account
from dataSet1)z
Where Not exists (Select * from dataSet2
                  where cust_ref = z.CustRef
                      and acc = z.account)

答案 2 :(得分:0)

WITH DataSet1 AS ( -- Define DataSet1
    SELECT *
    FROM (VALUES
        (1000001, 'ALPHA', 'BRAVO', 'CHARLIE')
      , (1000002, 'ALPHA', 'BRAVO', 'CHARLIE')
      , (1000003, 'ALPHA', 'BRAVO', 'CHARLIE')
      , (1000004, 'DELTA', 'ECHO', NULL)
      , (1000005, 'DELTA', 'ECHO', NULL)
      , (1000006, 'FOXTROT', NULL, NULL)
      , (1000007, 'FOXTROT', NULL, NULL)
    ) A (Cust_Ref, ACC1, ACC2, ACC3)
), DataSet2 AS ( -- Define DataSet2
    SELECT *
    FROM (VALUES
        (1000001, 'ALPHA')
      , (1000001, 'BRAVO')
      , (1000004, 'DELTA')
      , (1000004, 'ECHO')
      , (1000006, 'FOXTROT')
    ) A (Cust_Ref, ACC)
)
SELECT A.Cust_Ref
     , B.ACC
FROM DataSet1 A
CROSS APPLY(VALUES -- Pivot ACC1, ACC2, and ACC3 into ACC
    (A.ACC1)
  , (A.ACC2)
  , (A.ACC3)
) B (ACC)
WHERE B.ACC IS NOT NULL -- Remove NULL ACCs
  AND NOT EXISTS ( -- Remove ACCs that exist in DataSet2
    SELECT 1
    FROM DataSet2
    WHERE A.Cust_Ref = Cust_Ref
      AND B.ACC = ACC
);