select - Combining two SQL tables with common columns -


i have 2 tables want combine one. have common columns, can't figure out how combine them properly.

samples:

table a

month | year | costumer_id | total_a | --------------------------------------   10  | 2014 |    222      |   50    |     1  | 2015 |    111      |  100    |    2  | 2015 |    111      |  200    |    4  | 2015 |    222      |  250    | 

table b

month | year | costumer_id | total_b | --------------------------------------   1   | 2015 |    111      |   50    |   2   | 2015 |    333      |  100    |   4   | 2015 |    222      |  250    | 

desired result

month | year | costumer_id | total_a | total_b | ------------------------------------------------  10   | 2014 |    222      |   50    |     0   |   1   | 2015 |    111      |  100    |    50   |   2   | 2015 |    111      |  200    |     0   |   2   | 2015 |    333      |    0    |   100   |   4   | 2015 |    222      |  250    |   250   | 

the logic following:

in table each month in each year if total_a of client not zero, there record in table. therefore, not months of each year have record each client.

table b works same way table total_b different total_a. therefore, specific month , year, client may have record in 1 table, in both or in none of them.

i want generate table containing records each client each month in each year. if there corresponding record in table or table b, total_a , total_b of each table shown in resulting table. if there not record specific client in specific month , year in of tables, total_a or/and total_b 0 in resulting table.

this looks full outer join. 0s can generated coalesce:

select coalesce(a.month, b.month) month,         coalesce(a.year, b.year) year,         coalesce(a.customerid, b.customerid) customerid,         coalesce(total_a, 0) total_a,         coalesce(total_b, 0) total_b   full outer join b on a.month = b.month ,                      a.year = b.year ,                      a.customerid = b.customerid 

Comments

Popular posts from this blog

Email notification in google apps script -

c++ - Difference between pre and post decrement in recursive function argument -

javascript - IE11 incompatibility with jQuery's 'readonly'? -