合并不同表中的日期列

Merge date columns in different tables

我正在尝试合并月份列并连接来自两个不同 table 的数据。我已经尝试过 union all 和 full join 但结果并不像我预期的那样。我想要 1 个月的列和其他 4 个列(如果它们具有空值则无关紧要)非常感谢!

这是我想要的结果:

month    | new_placements | new_mrr | exits | lost_mrr
20190101 | null           | null    | 8     | 19900
20181101 | 144            | 148000  | null  | null

来自这两个 table:

table1

month1   | new_placements | new_mrr 
20181101 | 144            | 148000

table2

month    | exits          | lost_mrr
20190101 | 8              | 19900

规格完全不清楚。

以下查询将满足规范的一种可能解释:

SELECT n.month1                AS month_column
     , n.new_placements        AS new_placements
     , n.new_mrr               AS new_mrr
     , ''                      AS exits
     , ''                      AS lost_mrr
  FROM table1 n
 UNION ALL
SELECT o.month                 AS month_column
     , ''                      AS new_placements
     , ''                      AS new_mrr
     , o.exits                 AS exits
     , o.lost_mrr              AS lost_mrr
  FROM table2 o

--

编辑

对于问题中显示的数据(左对齐),值似乎是字符串而不是数值。数值将右对齐。理想情况下,我们应该知道列的数据类型,最好是两个表的实际定义。我们可以创建并填充上面的查询不会引发错误的示例表。)

使用 UNION ALL 集合运算符,每个集合必须具有相同的列数,并且每个列位置需要具有相同(或兼容)的数据类型。

SELECT n.month1                AS month_column
     , n.new_placements        AS new_placements
     , n.new_mrr               AS new_mrr
     , NULL                    AS exits
     , NULL                    AS lost_mrr
  FROM table1 n
 UNION ALL
SELECT o.month                 AS month_column
     , NULL                    AS new_placements
     , NULL                    AS new_mrr
     , o.exits                 AS exits
     , o.lost_mrr              AS lost_mrr
  FROM table2 o
SELECT month_column
     , max(new_placements) as new_placements
     , max(new_mrr) as new_mrr
     , max(exits) as exits
     , max(lost_mrr) as lost_mrr
  from (SELECT n.month1                AS month_column
             , n.new_placements        AS new_placements
             , n.new_mrr               AS new_mrr
             , null                    AS exits
             , null                    AS lost_mrr
          FROM table1 n
        UNION ALL
        SELECT o.month 
             , null 
             , null
             , o.exits
             , o.lost_mrr
          FROM table2 o) as a
GROUP BY month_column;