从其他表中获取匹配数据的ID。两个表中没有重复的ID

时间:2018-02-20 13:25:23

标签: sql sql-server

这是我的表A.

| Id |  GroupId  |  StoreId  | Amount |
| 1  |    20     |     7     |  15000 |
| 2  |    20     |     7     |   1230 |
| 3  |    20     |     7     |  14230 |
| 4  |    20     |     7     |   9540 |
| 5  |    20     |     7     |  24230 |
| 6  |    20     |     7     |   1230 |
| 7  |    20     |     7     |   1230 |

这是我的表B.

| Id  |  GroupId  |  StoreId  | Credit |
| 12  |    20     |     7     |   1230 |
| 14  |    20     |     7     |  15000 |
| 15  |    20     |     7     |  14230 |
| 16  |    20     |     7     |   1230 |
| 17  |    20     |     7     |   7004 |
| 18  |    20     |     7     |  65523 |

我想获得此结果而不会获得两个表的重复ID。 我需要获得表B和A的Id,其中Amount = Credit。

 |  A.ID     |   B.ID    |  Amount |
 |    1      |     14    |   15000 |
 |    2      |     12    |    1230 |
 |    3      |     15    |   14230 |
 |    4      |     null  |    9540 |
 |    5      |     null  |   24230 |
 |    6      |     16    |    1230 |
 |    7      |     null  |    1230 |

我的问题是当我在表A中有2个或更多相同金额时,我得到表B的重复ID,它应该为null。请帮我。谢谢。

2 个答案:

答案 0 :(得分:2)

我想你想要left join。但这很棘手,因为你有重复的金额,但你只想要一个匹配。解决方案是使用row_number()

select . . .
from (select a.*, row_number() over (partition by amount order by id) as seqnum
      from a
     ) a left join
     (select b.*, row_number() over (partition by credit order by id) as seqnum
      from b
     )b
     on a.amount = b.credit and a.seqnum = b.seqnum;

答案 1 :(得分:1)

另一种方法,我认为更简单,更短:)

select ID [A.ID],
       (select top 1 ID from TABLE_B where Credit = A.Amount) [B.ID],
       Amount
from TABLE_A [A]