0

我正在尝试在 SQL Server 中合并 2 个表

表格1:SO

ItemCode     | SONumber| SODate     | SOQTY
-------------------------------------------
TBJ182-01-02 | 0005251 | 29/01/2014 | 5
TBJ184-01-02 | 0005251 | 29/01/2014 | 2
TBJ182-01-02 | 0005554 | 15/02/2014 | 4
TBJ185-01-02 | 0005554 | 15/02/2014 | 5

表 2:PO

ItemCode     | PONumber| PODate     | POQTY
--------------------------------------------
TBJ182-01-02 | 0009105 | 11/02/2014 | 8
TBJ184-01-02 | 0009208 | 14/02/2014 | 5
TBJ189-01-02 | 0009208 | 14/02/2014 | 5

结果表:

ItemCode     | SONumber| SODate    | SOQTY | PONmber |PODate      | POQTY
-------------------------------------------------------------------------
TBJ182-01-02 | 0005251 | 29/01/2014| 5     |         |            |
TBJ184-01-02 | 0005251 | 29/01/2014| 2     |         |            |
TBJ182-01-02 | 0005554 | 15/02/2014| 4     |         |            |
TBJ185-01-02 | 0005554 | 15/02/2014| 5     |         |            |
TBJ182-01-02 |         |           |       | 0009105 | 11/02/2014 | 8
TBJ184-01-02 |         |           |       | 0009208 | 14/02/2014 | 5
TBJ189-01-02 |         |           |       | 0009208 | 14/02/2014 | 5

你能帮忙吗?

4

2 回答 2

2

full outer join您可以通过一个小技巧最轻松地做到这一点:

select coalesce(SO.ItemCode, PO.ItemCode) as ItemCode,
       SO.SONumber, SO.SODate, SO.SOQTY,
       PO.PONmber, PO.PODate, PO.POQTY
from SO full outer join
     PO
     on 1 = 0;
于 2014-04-30T21:38:16.980 回答
0

我没有再修改删除外部和 ISNULL 来代替合并

DECLARE @Tbl TABLE (


     ITEMCode VARCHAR(100),
        SONUMBER VARCHAR(100), 
        SoQTY INT
    )

    INSERT INTO @Tbl VALUES ('TBJ182-01-02','0005251',1)
    INSERT INTO @Tbl VALUES ('TBJ184-01-02', '0005251', 2)
    INSERT INTO @Tbl VALUES ('TBJ182-01-02', '0005554',4)
    INSERT INTO @Tbl VALUES ('TBJ182-01-02', '0005554',6)

    DECLARE @Tbl1 TABLE (
        ITEMCode VARCHAR(100),
        PONUMBER VARCHAR(100), 
        POQTY INT
    )

    INSERT INTO @Tbl1 VALUES ('TBJ182-01-02','0005251',1)
    INSERT INTO @Tbl1 VALUES ('TBJ184-01-02', '0005251', 2)
    INSERT INTO @Tbl1 VALUES ('TBJ182-01-02', '0005554',4)
    INSERT INTO @Tbl1 VALUES ('TBJ182-01-02', '0005554',6)
    select ISNULL(t.ITEMCode,tt.ITEMCode),t.SONUMBER,t.SoQTY,tt.PONUMBER,tt.POQTY from @Tbl t
    FULL JOIN @Tbl1 tt
    ON 1 = 0
于 2014-05-01T07:01:17.550 回答