将来自不同表的三个或更多相同列的数据合并为单个列

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

我有三个不同的表格,其中包含月份和项目,如下所示: 表 1

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

表 2

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

表 3

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

现在,我看起来像这样: 月书复印笔 - 应合并月份列,其他数据应放在相应的列中(如果没有可用数据,则应放置 0),例如

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

我试过

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 不会工作,因为它给了我 6 列(3 个月,我只需要 1)

我知道的最好的方法是将月份提取为工作-table,然后依次左连接每个源 table 以逐个提取列一。如果您知道每个 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

您可以使用 full join 执行此操作。它看起来像这样:

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

就个人而言,我发现 union all/group by 方法可能是最直观的:

select month,
       sum(books) as books, sum(copies) as copies, sum(pens) as pens
from ((select month, books, 0 as copies, 0 as pens from #table1
      ) union all
      (select month, 0 as books, copies, 0 as pens from #table2
      ) union all
      (select month, 0 as books, 0 as copies, pens from #table3
      )
     ) bcp
group by month;

Mike建议的left join方法也很合理;通常,我不想在两个地方列出每个 table。如果我稍后更新查询,这可能会导致错误。