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

时间:2016-07-08 16:04:49

标签: sql sql-server join union coalesce

我有三个不同的表,月份和项目如下: 表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

---联盟不会工作,因为它给了我6列(3个月,我只需要1个)

2 个答案:

答案 0 :(得分:3)

我知道这样做的最好方法是将月份提取为工作表,然后依次连接每个源表以逐个拾取列。如果您知道每个表中有相同的月份列表,那么提取月份是不必要的。

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

答案 1 :(得分:2)

您可以使用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;

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