Table 1
item | unit sold | item - 2 | unit sold |
---|---|---|---|
x | 1000 | y | 500 |
Table 2
bundle items | items in bundle |
---|---|
a | ['x,y'] |
b | ['x,y,z'] |
I need to join Table 1 & 2. If Item and item-2 match with items in bundle.
Desired result
item | unit sold | item - 2 | unit sold | bundle items | items in bundle |
---|---|---|---|---|---|
x | 1000 | y | 500 | a | [x,y] |
x | 1000 | y | 500 | b | [x,y,z] |
I tried using unnest with no luck.
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)
CodePudding user response:
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.
CodePudding user response:
Consider below query.
I need to join Table 1 & 2. If Item and item-2 match with items in 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