通过比较两个表来选择不在另一个表中的行

时间:2014-01-27 09:48:15

标签: sql sql-server sql-server-2008

我有以下两个表 TableA TableB

表A

Id  Month_Id    Customer_Id   Total_Amount
1    1          1               50
2    2          1              150
3    3          1              200
4    1          2               75
5    2          2              100
6    1          3              400
7    2          3              200

表B

Id  Month_Id    Customer_Id         Total_Amount
1     1               1             50
2     2               1            150
3     1               2             75

我想在两个表格中比较 Month_Id Customer_Id Total_Amount ,然后从 TableA <中选择 ID / strong>即可。输出应如下所示。

输出

Id
3
5
6
7

我的理念是:

SELECT TableA.Id FROM TableA 
WHERE TableA.Month_Id <> TableB.MonthId AND
TableA.Customer_Id <> TableB.Customer_Id AND
TableA.Total_Amount <> TableB.Total_Amount

7 个答案:

答案 0 :(得分:1)

select Id 
from (
select Id, Month_Id,    Customer_Id,   Total_Amount from TableA    
except     
select Id, Month_Id,    Customer_Id,   Total_Amount from TableB
) q

答案 1 :(得分:1)

    SELECT TableA.Id
    FROM TableA
    WHERE NOT EXISTS (
      SELECT 1
      FROM TableB
      WHERE TableB.Month_Id = TableA.Month_Id
      AND TableB.Customer_Id = TableA.Customer_Id
      AND TableB.Total_Amount = TableA.Total_Amount
   )

答案 2 :(得分:1)

SELECT id FROM
     (SELECT id, month_id, customer_id, total_ammount FROM TableA
      EXCEPT    
      SELECT id, month_id, customer_id, total_ammount FROM TableB);

答案 3 :(得分:1)

您可以使用EXCEPT设置运算符:

SELECT id 
FROM   (SELECT * FROM table_a
        EXCEPT
        SELECT * FROM table_b) t

答案 4 :(得分:0)

您可以将MergeWHEN NOT MATCHED

一起使用

将您的情况置于ON <merge_search_condition>

答案 5 :(得分:0)

在oracle sql中它将是:

SELECT ID FROM
   (SELECT ID, Month_Id, Customer_Id, Total_Amount FROM TABLE_A
    MINUS 
    SELECT ID, Month_Id, Customer_Id, Total_Amount FROM TABLE_B);
这是你想要的吗? (虽然不确定sql-server中的MINUS运算符)

答案 6 :(得分:0)

SELECT Id FROM TableA A LEFT JOIN tableB B 
    ON  A.Id=B.Id AND A.Month_Id =B.Month_Id  
    AND A.Customer_Id   =B.Customer_Id  
    AND A.Total_Amount=b.Total_Amount
WHERE B.Id is NULL