What's the best way to write if/else if/else if/else in HIVE?

假如想象 提交于 2020-01-20 04:32:05

问题


Hive uses IF(condition, expression, expression), so when I want to do if / else if / else if / else, I have to do:

IF(a, 1, IF(b, 2, IF(c, 3, 4)))

Is there a better way to do this that's more readable?

Looking for something similar to the standard

if (a) {
  1
} else if (b) {
  2
} else if (c) {
  3
} else {
  4
}

回答1:


You can use Hive Conditional CASE WHEN function for if-else scenario. The CASE Statement will provide you better readability with the same functionality.

CASE
  WHEN (condition1) THEN result1
  WHEN (condition2) THEN result2
  WHEN (condition3) THEN result3 
  WHEN (condition4) THEN result4
  ELSE result_default 
END AS attribute_name



回答2:


The best way to handle if else will be to write customize UDF for particular column.




回答3:


You can easily achieve this using CASE WHEN statements.

CASE 
    WHEN a THEN 1
    WHEN b THEN 2
    WHEN c THEN 3
    ELSE 4
END AS attribute_name

For more information, refer official doc at https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-ConditionalFunctions



来源:https://stackoverflow.com/questions/32472801/whats-the-best-way-to-write-if-else-if-else-if-else-in-hive

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!