Search code examples
sqljoinselectunionoracle12c

Selecting values from two different tables-sql


I have two tables A and B with the same columns ID, Date, Main_id, Quantity. Main_id is a similar column for both the tables. I want to select ID, Date, a.quantity, b.quantity into table c.

A:

id |  date         |  main_id   | quantity_in
----------------------------------------------
12   4/10/2019      1                60
20   7/4/2019        2                30 
33    9/6/2019       3                10

B:

id |  date         |  main_id   | quantity_out
----------------------------------------------
20   5/10/2019          1               10
40   7/4/2019           1               30 
53    9/6/2019          1               10

C: result table

id   |  date            |  main_id   | quantity_In  |   quantity_out
------------------------------------------------------------------
12    4/10/2019              1                60            null
20    5/10/2019              1               null            10
40    7/4/2019               1               null            30 
53    9/6/2019               1               null            10

Solution

  • You seem to want union all:

    select a.id, a.date, a.main_id, a.quantity_in, null as quantity_out
    from a
    where a.main_id = 1
    union all
    select b.id, b.date, b.main_id, null as quantity_in, b.quantity_out
    from b
    where b.main_id = 1;