将Google BigQuery中的表格与UNION ALL合并

时间:2019-03-06 23:26:12

标签: sql google-bigquery

我想在BQ做类似的事情。这些表具有不同的架构。任何想法如何实现这一目标?

SELECT YYYYMMDDHH, CONTAINER, Parent_Container, PROTOTYPE_ID, Withdrawal_this_hour FROM `tb1`
UNION ALL
SELECT YYYYMMDDHH, CONTAINER, Parent_Container, PROTOTYPE_ID, Refill_this_hour FROM `tb2` 
UNION ALL
SELECT YYYYMMDDHH, CONTAINER, Parent_Container, PROTOTYPE_ID, changes_this_hour, net_amount, date from `tb3`

先谢谢了。

2 个答案:

答案 0 :(得分:2)

列必须相同,所以像这样:

SELECT YYYYMMDDHH, CONTAINER, Parent_Container, PROTOTYPE_ID,
       Withdrawal_this_hour, NULL as Refill_this_hour,
       NULL as changes_this_hour, NULL as net_amount, NULL as date 
FROM `tb1`
UNION ALL
SELECT YYYYMMDDHH, CONTAINER, Parent_Container, PROTOTYPE_ID,
       NULL, Refill_this_hour, NULL, NULL, NULL
FROM `tb2` 
UNION ALL
SELECT YYYYMMDDHH, CONTAINER, Parent_Container, PROTOTYPE_ID,
       NULL, NULL, changes_this_hour, net_amount, date 
FROM `tb3`

答案 1 :(得分:0)

要进行并集,所有表big query docs的列数及其数据必须相同,您可以使用cte尝试如下所示

  with cte as  (

   SELECT YYYYMMDDHH, CONTAINER, Parent_Container, PROTOTYPE_ID,
   Withdrawal_this_hour, NULL as Refill_this_hour,
   NULL as changes_this_hour, NULL as net_amount, NULL as date
  UNION ALL
  SELECT YYYYMMDDHH, CONTAINER, Parent_Container, PROTOTYPE_ID,
   NULL, Refill_this_hour, NULL, NULL, NULL FROM tb2
   UNION ALL
  SELECT YYYYMMDDHH, CONTAINER, Parent_Container, PROTOTYPE_ID,
   NULL, NULL, changes_this_hour, net_amount, date 
  FROM tb3
 ) select * from cte