需要两张表中的表格才能获得

时间:2018-01-29 02:03:19

标签: sql-server

TABLE_1

Customer_ID      Sub_ID         
-----------------------         
12345            100            
23456            200            
34567            300            
45678            400            
56789            500            

TABLE_2

Customer_ID     Sub_ID
----------------------
12345           101
12345           300
12345           103
23456           200
23456           200
23456           100     
34567           300
34567           300
45678           300
56789           800

期望的结果

Customer_ID     Sub_ID
-------------------
34567           300

在Table_1中,Customer_ID没有重复项,每个Customer_ID只有一个Sub_ID。 Table_2可以具有Duplicate Customer_ID和多个或单个Sub_Id。需要仅在Table_2中找到与Customer_1和Sub_ID完全匹配Table_1 Customer_ID和Sub_ID

的Customer_ID和Sub_ID的区别

我的尝试:

SELECT  Customer_ID,Sub_ID  
FROM Table_A A  
WHERE A.Customer_ID,A.Sub_ID not in (SELECT B.Customer_ID,B.Sub_ID
                  FROM Table_B B);

2 个答案:

答案 0 :(得分:0)

select * from table1 t1 inner join table2 t2
on t1.customer_id=t2.customer_id and t1.sub_id=t2.sub_id
and t1.customer_id not in 
(select t3.customer_id from table1 t3 inner join table2 t4 
on t3.customer_id=t4.customer_id and t3.sub_id <> t4.sub_id)

答案 1 :(得分:0)

您可以简单地编写您的查询,如下所示。

SELECT DISTINCT T2.CUSTOMER_ID, 
                T2.SUB_ID 
FROM   TABLE_1 T1 
       INNER JOIN TABLE_2 T2 
               ON T1.CUSTOMER_ID = T2.CUSTOMER_ID 
                  AND T1.SUB_ID = T2.SUB_ID 
WHERE  NOT EXISTS (SELECT 1 
                   FROM   TABLE_2 TI 
                   WHERE  TI.CUSTOMER_ID = T1.CUSTOMER_ID 
                          AND TI.SUB_ID <> T1.SUB_ID) 

这将为您提供所需的输出。