Hive中if函数和Mysql中ifnull的转换

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Luomingkui1109/article/details/85051941

1.在mysql中,ifnull函数的用法,其表达式如下:

    IFNULL(expr1,expr2)

    如果 expr1 不是 NULL,IFNULL() 返回 expr1,否则它返回 expr2。IFNULL()返回一个数字或字符串值,取决于它被使用的上下文环境。

    举个应用场景,比如某一个字段定义为int类型,其默认值为0,但是在sql查询过程中,有可能出现为null,这个时候,我们就可以用ifnull来判断一下,如果结果为null,就给默认值0,下面给出一个实例:

CREATE TABLE dws_consignee_summary STORED AS PARQUET AS SELECT        concat_ws(',',ifnull(delivery_province,'0'),ifnull(delivery_city,'0'),ifnull(delivery_district,'0'),ifnull(delivery_village,'0'),ifnull(picking_address,'0')) AS consignee_address,

        substr(create_time,1,7) AS month

FROM ods_g2matrix_sale_order;

    然而,在hive写HQL的时候,ifnull函数是不存在的,但是,可以使用if(col is not null, col, default_value)来实现ifnull的功能,如果col不为null,返回col的值,否则返回default_value。

    那上面的实例就可以改成如下:

CREATE TABLE dws_consignee_summary_base STORED AS PARQUET AS SELECT

        concat_ws(',',if(delivery_province IS NOT NULL ,delivery_province,'0'),if(delivery_city IS NOT NULL,delivery_city,'0'),if(delivery_district IS NOT NULL,delivery_district,'0'),if(delivery_village IS NOT NULL,delivery_village,'0'),if(picking_address IS NOT NULL,picking_address,'0')) AS consignee_address,

        substr(create_time,1,7) AS month

FROM ods_g2matrix_sale_order;

猜你喜欢

转载自blog.csdn.net/Luomingkui1109/article/details/85051941
今日推荐