如何将来自两个不同表的两列合并为一列

问题描述 投票:0回答:1

我有两个表,分别包含苹果和三星的销售数据

Apple销售表

cust_id | apple_products 
0001      iPad
0002      iPhone
0002      Apple Watch
0003      Macbook
0003      Apple Watch

三星销售表

cust_id | samsung_products 
0001      Galaxy S10
0002      Galaxy Tab 1
0004      Galaxy Tab 2
0004      Galaxy Note

我想知道如何编写查询以合并这两个表

总销售额表

cust_id | products 
0001      Galaxy S10
0001      iPad
0002      Galaxy Tab 1
0002      iPhone
0002      Apple Watch
0003      Macbook
0003      Apple Watch
0004      Galaxy Tab 2
0004      Galaxy Note

我正在考虑使用UNION ALL,但是我不确定这是否是最好的方法。这是我正在使用的查询。

select 
  cust_id
  , apple_products as products
from apple_sales
UNION ALL
  cust_id
  , samsung_products
from samsung_sales
google-bigquery union union-all
1个回答
0
投票

联合会很好。要真正拥抱BigQuery,请考虑:

with unioned as (
  select cust_id, 'Apple' as brand, apple_products as product from apple_sales
  union all
  select cust_id, 'Samsung' as brand, samsung_products as product from samsung_sales
)
select
  cust_id,
  array_agg(struct(brand,product)) as devices
from unioned
group by 1
© www.soinside.com 2019 - 2024. All rights reserved.