简体   繁体   English

BigQuery - 在数组列上连接表

[英]BigQuery - Join table on Array column

Table 1表格1

item物品 unit sold售出单位 item - 2项目 - 2 unit sold售出单位
x X 1000 1000 y 500 500

Table 2表 2

bundle items捆绑物品 items in bundle捆绑物品
a一种 ['x,y'] ['x,y']
b b ['x,y,z'] ['x,y,z']

I need to join Table 1 & 2. If Item and item-2 match with items in bundle.我需要加入表 1 和表 2。如果 Item 和 item-2 与 bundle 中的项目匹配。

Desired result期望的结果

item物品 unit sold售出单位 item - 2项目 - 2 unit sold售出单位 bundle items捆绑物品 items in bundle捆绑物品
x X 1000 1000 y 500 500 a一种 [x,y] [x,y]
x X 1000 1000 y 500 500 b b [x,y,z] [x,y,z]

I tried using unnest with no luck.我尝试使用 unnest 但没有运气。

Left join (
    select b_sku, array_agg(c_sku) as children 
    from p
    group by p.b_sku
  ) y
ON i.sku = unnest(y.children)

Here is a solution that might work for you:这是一个可能适合您的解决方案:

with table_a as (
  select 'x' as item, 1000 as unit_sold union all
  select 'y' as item, 500 as unit_sold union all
  select 'k' as item, 500 as unit_sold
),
table_b as (
  select 'x' as bundle_item, ['x', 'y'] as items_in_bundle union all
  select 'y' as bundle_item, ['x', 'y', 'z'] as items_in_bundle union all
  select 'k' as bundle_item, ['x', 'y', 'z'] as items_in_bundle
)
select * from table_a a 
left join  table_b b on a.item = b.bundle_item
where a.item in unnest(b.items_in_bundle)

As a result row with 'k' item wouldn't be joined because 'k' item is out of 'items_in_bundle' array.结果,带有“k”项的行不会被加入,因为“k”项不在“items_in_bundle”数组中。

Consider below query.考虑以下查询。

I need to join Table 1 & 2. If Item and item-2 match with items in bundle.我需要加入表 1 和表 2。如果 Item 和 item-2 与 bundle 中的项目匹配。

WITH table1 AS (
  SELECT 'x' item, 1000 unit_sold, 'y' item_2, 500 unit_2_sold
),
table2 AS (
  SELECT 'a' bundle_items, ['x', 'y'] items_in_bundle UNION ALL
  SELECT 'b', ['x', 'y', 'z'] UNION ALL
  SELECT 'c', ['x', 'u', 'v']
)
SELECT *
  FROM table1 t1 LEFT JOIN table2  t2 
    ON t1.item IN UNNEST(t2.items_in_bundle) 
   AND t1.item_2 IN UNNEST(t2.items_in_bundle);

Query results查询结果

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM