完全外部加入重复结果

时间:2017-12-08 00:13:11

标签: sql

美好的一天,

这可能看起来很长(但这是我正在展示的数据)我有两张桌子。 TestA和TestB。 TestA有两列(INT,VARCHAR(32)),称为RowNumber和InvoiceNumber。以下结果是:SELECT RowNumber,InvoiceNumber FROM TestA。

1   GB01530111600236
2   GB01530111600236
3   GB01530111600236
1   GB01530121600001
2   GB01530121600001

TestB的相同之处在于有两列具有相同的名称。

1   GB01530111600236
1   GB01530121600001
2   GB01530121600001
3   GB01530121600001
4   GB01530121600001
5   GB01530121600001
6   GB01530121600001
7   GB01530121600001
8   GB01530121600001
9   GB01530121600001
10  GB01530121600001
11  GB01530121600001
12  GB01530121600001

我对FULL OUTER JOIN的理解是它将基于JOIN和WHERE子句匹配来自两个表的所有行。原因是TableA可以有一个或多个发票号,TableB也可以有一个或多个发票号。

因此,从TestA,有三个发票编号为'GB01530111600236',一个在TestB中有'GB01530111600236'。此外,TestB中有12个发票编号为“GB01530121600001”,TestA中有两个发票编号为“GB01530121600001”所以我想要的是:

[   Table A        ]    [   Table B        ]
1   GB01530111600236    1   G01530111600236
2   GB01530111600236    1   G01530111600236
3   GB01530111600236    1   G01530111600236
1   GB01530121600001    1   GB01530121600001
2   GB01530121600001    2   GB01530121600001
1   GB01530121600001    3   GB01530121600001
1   GB01530121600001    4   GB01530121600001
1   GB01530121600001    5   GB01530121600001
1   GB01530121600001    6   GB01530121600001
1   GB01530121600001    7   GB01530121600001
1   GB01530121600001    8   GB01530121600001
1   GB01530121600001    9   GB01530121600001
1   GB01530121600001    10  GB01530121600001
1   GB01530121600001    11  GB01530121600001
1   GB01530121600001    12  GB01530121600001

我的查询是:

SELECT A.RowNumber, B.RowNumber, A.InvoiceNumber, B.InvoiceNumber
FROM TestA A 
    FULL OUTER JOIN TestB B ON A.InvoiceNumber = B.InvoiceNumber

这个查询是正确的一半,因为它为'GB01530111600236'提供了正确的输出。删节版只显示1-5而不是1到12。

1   GB01530111600236    1   GB01530111600236
2   GB01530111600236    1   GB01530111600236
3   GB01530111600236    1   GB01530111600236
1   GB01530121600001    1   GB01530121600001
1   GB01530121600001    2   GB01530121600001
1   GB01530121600001    3   GB01530121600001
1   GB01530121600001    4   GB01530121600001
1   GB01530121600001    5   GB01530121600001
2   GB01530121600001    1   GB01530121600001
2   GB01530121600001    2   GB01530121600001
2   GB01530121600001    3   GB01530121600001
2   GB01530121600001    4   GB01530121600001
2   GB01530121600001    5   GB01530121600001

但是对于第二个发票号码'GB01530121600001',它给了我重复的信息。我如何摆脱重复?

TIA,

COSON

1 个答案:

答案 0 :(得分:0)

我没有遵循结果集的逻辑。但是,以下内容应该给出相同的结果:

SELECT COALESCE(A.RowNumber, 1),
       COALESCE(B.RowNumber, 1),
       COALESCE(A.InvoiceNumber, B.InvoiceNumber),
       COALESCE(A.InvoiceNumber, B.InvoiceNumber)
FROM TestA A FULL OUTER JOIN
     TestB B
     ON A.InvoiceNumber = B.InvoiceNumber AND
        A.RowNumber = B.RowNumber;