select 如何只匹配每个值一次?

How can a select match each value only once?

我正在匹配来自 table1table2 的金额值,table 具有重复项和不同的行数。任何金额只能匹配一次(因此不是标准 select 的工作方式),因为 select 中 table 的总金额应该保持不变,就好像我添加了所有插入的值一样table.

CREATE TABLE table1 (
    table1_amount int
);
INSERT INTO table1 (table1_amount)
VALUES
    (22),
    (11),
    (35),
    (45),
    (45),
    (65),
    (22),
    (22),
    (878),
    (56);

CREATE TABLE table2 (
    table2_amount int
);
INSERT INTO table2 (table2_amount)
VALUES
    (324),
    (43),
    (34),
    (35),
    (22),
    (22),
    (12),
    (35),
    (6);

标准 select 将 return 6 行匹配 table1 中的三个“22”到 table2 中的两个“22”(因此每个“22”来自 table1 匹配两次):

SELECT table1.table1_amount, table2.table2_amount
FROM table1 FULL OUTER JOIN table2 ON table1.table1_amount=table2.table2_amount;

table1_amount table2_amount
22 22
22 22
22 22
22 22
22 22

现在,我只想从 table1 中获得 2 个匹配项 + 1 个不匹配项,所以:

table1_amount table2_amount
22 22
22 22
22 NULL

你怎么做到的?我在这里指出 SQL 但任何解决方案 (Excel, Access) 都会很好。

尝试使用 Row_Number():

with cte1 as
(Select *, ROW_NUMBER() over (partition by table1_amount order by table1_amount) as ranking from table1),
 cte2 as
(Select *,ROW_NUMBER() over (partition by table2_amount order by table2_amount) as ranking from table2)
Select cte1.table1_amount, cte2.table2_amount from cte1 FULL OUTER JOIN cte2 on cte1.table1_amount = cte2.table2_amount and cte1.ranking = cte2.ranking

试试这个:

selectcte1.table1_amount,cte2.table2_amount from (Select *, ROW_NUMBER() over (partition by table1_amount order by table1_amount) as ranking from @table1) as cte1 left join (Select *,ROW_NUMBER() over (partition by table2_amount order by table2_amount) as ranking from @table2) as cte2 on cte1.table1_amount = cte2.table2_amount 和 cte1.ranking = cte2.ranking