Search code examples
sqlsql-serverjoinunioncoalesce

Merge data from three or more identical columns of different tables into single column


I have three different tables with month and item as follows: Table1

month books
April-2016  2
February-2016   7
January-2016    1
June-2016   6
May-2016    1
September-2015  1

Table2

month copies
April-2016  92
August-2015 1
February-2016   49
January-2016    5
June-2016   127

Table3

month pens
February-2016   74
January-2016    1
June-2016   66
March-2016  136
May-2016    128

Now, I was looking something like this: month books copies pens -the month column should be merged and other data should be placed in respective column (if no data is available then 0 should be placed) such as

month books copies pens
April-2016  2 92 0
September-2015  1 0 0
August-2015 0 1 0
June-2016   6 127 66

I tried with

select COALESCE(t1.Month,t2.Month,t3.Month) AS [Month],
ISNULL(t1.books,0) AS books,
ISNULL(tp.copies,0) AS copies,
ISNULL(tn.pens,0) AS pens
from  #table1 t1
full join #table t2 on t1.month=t2.month
full join #table t3 on t1.month=t3.month

---Union won't work as it is giving me 6 columns ( 3 for months, where i need only 1)


Solution

  • The best way I know to do this is to extract the months as a work-table and then left join each of the source tables in turn to pick up the columns one by one. The extraction of the months isn't necessary if you know there's an identical list of months in each table.

    select a.month,
           t1.books,
           t2.copies,
           t3.pens
      from (
    select month from table1
    union
    select month from table2
    union
    select month from table3) a
    left join table1 t1
        on a.month = t1.month
    left join table2 t2
        on a.month = t2.month
    left join table3 t3
        on a.month = t3.month