HIVE SQL中CASE WHEN不支持子查询的解决方法

5 篇文章 1 订阅

在以下业务场景中,我们有一张订单表,订单表中有产品的编号,我们需要匹配出产品所属的品牌名称。不同品牌的产品名称分别存放在不同的产品清单表中。
在这里插入图片描述

在MySQL等关系型数据库中,可以使用case when+in(子查询)的方式来匹配订单表中的产品所属的品牌名称。

select product_code
	,product_quantity
	,case when product_code in (select product_code from table_a)
		  then 'BRAND_A'
		  when product_code in (select product_code from table_b)
		  then 'BRAND_B'
		  when product_code in (select product_code from table_c)
		  then 'BRAND_C'
		  else null
	  end as brand_name
from 
table_order

但是在HIVE SQL中,如果执行该查询语句,就会报错,提示Currently SubQuery expressions are only allowed as Where Clause predicates
这个时候可以使用left join来解决。

with tmp1 as
(
select product_code
	,product_quantity
	,case when t2.product_code is not null then 'BRAND_A'
	      else null
	 end as brand_name
from
table_order t1
left join table_a t2
on t1.product_code=t2.product_code
)
,tmp2 as 
(
select product_code
	,product_quantity
	,case when t2.product_code is not null then 'BRAND_B'
	      else t1.brand_name
	 end as brand_name
from
tmp1 t1
left join table_b t2
on t1.product_code=t2.product_code
)
,tmp3 as 
(
select product_code
	,product_quantity
	,case when t2.product_code is not null then 'BRAND_C'
	      else t1.brand_name
	 end as brand_name
from
tmp2 t1
left join table_c t2
on t1.product_code=t2.product_code
)
select product_code,product_quantity,brand_name from tmp3;
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值