简体   繁体   中英

Hive join over partition

I have these 2 tables:

table products
(
product_id bigint, 
product_name string
)
partitioned by (product_category as string)

table place_of_sale
(
product_id bigint, 
city string
)
partitioned by (country as string)

how can I left join the 2 tables based on 'product_id' but over the partition 'country' of the table place_of_sale?

This is an example with the desired result:

table products
product_id      product_name    product_category
1000            banana          fruit
1001            coconut         fruit
1002            ananas          fruit
2002            cow             animal
2003            beef            animal


table place_of_sale
product_id      city        country
1000            Texas       USA
1002            Miami       USA
2003            Sydney      Australia


desired result for a left join between table products and table place_of_sale over the partition country :

product_id      product_name        product_category    city   country
1000            banana              fruit               Texas  USA
1001            coconut             fruit               null   null
1002            ananas              fruit               Miam   USA

2002            cow                 animal              null   null
2003            beef                animal              Sydney Australia

Here the example is given with only 2 different countries but imagine plenty of different countries. It's like a left join performed for each country and then an union between the results of all countries.

If the sold product is that present in the table place_of_sale, then use LEFT JOIN:

select s.country, p.product_id, p.product_name, p.category, 
       case when s.product_id is NULL then "not sold" else "sold" as sold 
 from products p
      left join place_of_sale s on p.product_id = s.product_id 
 order by country, product_id --order if necessary

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