Hive SQL 逻辑 - case when 语句

Posted

技术标签:

【中文标题】Hive SQL 逻辑 - case when 语句【英文标题】:Hive SQL logic - case when statement 【发布时间】:2020-04-16 00:59:36 【问题描述】:

我的查询:

case 
   when upper(a.camp_name) like "%Event%" and (upper(a.camp_name) not like "%Event-WBR%" or upper(a.camp_name) not like "%Event-Webinar%") THEN "Field"
   else "Demand"
end as Tactic

期望的输出:

Event-WBR = Demand
Event = Field

实际输出:

Event-WBR = Field
Event = Field

【问题讨论】:

【参考方案1】:

其实你应该把'or'换成'and'

case 
       when upper(a.camp_name) like "%Event%" and (upper(a.camp_name) not like "%Event-WBR%" and upper(a.camp_name) not like "%Event-Webinar%") THEN "Demand"
       else "Field"
    end as Tactic

但这里还有另外 2 个选项:

如果你只想为“事件”这个词做,你可以这样做

case 
   when upper(a.camp_name) like "%Event" and (upper(a.camp_name) not like "%Event-WBR%" or upper(a.camp_name) not like "%Event-Webinar%") THEN "Demand"
   else "Field"
end as Tactic

如果你只想排除这两个词,你可以这样做。

case 
   when upper(a.camp_name) like "%Event-WBR%" or (upper(a.camp_name) like "%Event-Webinar%" THEN "Field"
   else "Demand"
end as Tactic

【讨论】:

【参考方案2】:

你可以使用两个whens:

(case when (upper(a.camp_name) not like "%Event-WBR%" or 
            upper(a.camp_name) not like "%Event-Webinar%"
           ) then 'Event'
      when upper(a.camp_name) like "%Event%" then 'Event'
      else 'Deman'
 end) as tactic

【讨论】:

以上是关于Hive SQL 逻辑 - case when 语句的主要内容,如果未能解决你的问题,请参考以下文章

SQL中CASE WHEN THEN的用法

SQL 逻辑优化 case when 转为 union all

HIVE_case when

case when 用法

postgreSQL计算总数sum if case when

关于Hive中case when不准使用子查询的解决方法