简体   繁体   中英

Is there a way to have 1 to many relationship join in Big Query? I want to repeat values using full outer join but it returns inner join

I have a table with a ranking keywords and join another table where the keyword exists but when I apply an outer join, it only returns the inner join since there are multiple matches to 1.

What I have: 在此处输入图像描述

What I want:

在此处输入图像描述

I tried several different joins but it doesn't return what I want. It always returns an inner join.

You can achieve your desired output by joining each table separately and then applying union on those results.You can try the below query:

Query:

 create temp table main as (
 select 1 ranking, 'apple' keyword, 500 total_purchase union all
 select 2,'banana', 477  union all
 select 3, 'milk', 456
);
 
create temp table t1 as (
 select 1 ranking, 'apple' keyword, 55 purchase, 1 store union all
 select 2,'beer', 42 ,1  union all
 select 3, 'chips', 33 ,1
);
 
create temp table t2 as (
 select 1 ranking, 'apple' keyword, 51 purchase, 2 store union all
 select 2,'banana', 43 ,2  union all
 select 3, 'bread', 34 ,2
);
 
select m.*,t.purchase,first_value(Store ignore nulls) over
( order by m.ranking) store from main m
left join t1 t on m.keyword = t.keyword
union all
select m.*,t.purchase,first_value(Store ignore nulls) over( order by 
m.ranking) store from main m
left join t2 t on m.keyword = t.keyword

Output:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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