Search code examples
sqlsql-servercoalescefull-outer-join

Combine two tables - sql server


I'm trying to combine 2 tables in SQL Server

Table 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

Table 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

Result table:

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

Could you help?


Solution

  • You can do this most easily with a full outer join and a little trick:

    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;