Tsql比较结果集中的两个字段

时间:2015-06-05 00:29:01

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

我有两个表:table_A和table_W。我想只获得不匹配的付款细节和相应的说明。表格是:

table_W

adharno phone descrip_w amount_w
1       11    p1        100
2       22    p1        250
2       22    p2        250
2       22    p3        300
2       33    p1        150
2       33    p2        150
2       33    p3        400
3       55    p1        50
3       66    p1        100

TABLE_A

adharno phone decrip_a  amount_a
1       11    p1        110
2       22    p1        150
2       22    p2        150
2       22    p3        400
2       33    p1        250
2       33    p2        250
2       33    p3        300
3       55    p1        100
3       66    p1        50

我得到以下结果。

adharno phone descrip_w amount_w decrip_a amount_a
1       11    p1        100      p1       110
2       22    p1        250      p1       150
2       22    p2        250      p2       150
2       22    p3        300      p3       400
2       33    p1        150      p1       250
2       33    p2        150      p2       250
2       33    p3        400      p3       300
3       55    p1        50       p1       100
3       66    p1        100      p1       50

但我看的结果如下

adharno phone descrip_w amount_w decrip_a amount_a
1       11    p1        100      p1       110

我想比较匹配的descrip,即使phoneno不同但adhaarno应该相同。

1 个答案:

答案 0 :(得分:1)

怎么样:

SELECT w.adharno,
       w.phone w_phone,
       descrip_w,
       amount_w,
       a.phone a_phone,
       decrip_a,
       amount_a
FROM table_w w
JOIN table_a a ON a.adharno = w.adharno
              AND w.descrip_w = a.decrip_a
              AND (w.phone <> a.phone
                OR w.amount_w <> a.amount_a)