合并不同表格中的日期列

时间:2018-08-15 17:06:17

标签: mysql google-bigquery standard-sql

我正在尝试合并月份列,并连接来自两个不同表的数据。我已经尝试过全部加入并完全加入,但是并没有达到我的预期。我想有1个月的专栏,还有4个其他专栏(它们是否为空值都没关系),非常感谢!

这是我想要的结果:

HttpClientHandler

来自这两个表:

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

2 个答案:

答案 0 :(得分:1)

规范还不清楚。

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

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

答案 1 :(得分:1)

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;