简体   繁体   中英

How to overcome null data in concat Output Hive?

I have my query below:

SELECT
    day PERIOD,
    'DB_shop' TB_NAME,
    CONCAT(substring(cast(percentage AS STRING),1,5),'%') AS PERCENTAGE,
    CASE
        WHEN percentage >= 20 THEN concat('Data increase ', cast(percentage AS STRING),'% from last day')
        WHEN percentage <= -20 THEN concat('Data drop ', cast(percentage AS STRING),'% from last day')
        WHEN percentage IS NULL THEN "Data Not Found"
        ELSE 'Normal'
    END AS STATUS
FROM
(
    SELECT
        day,
        count(1) count_all,
        lag(count(1)) OVER(ORDER BY day) as PrevCount,
        round(((count(1) - lag(count(1)) OVER(ORDER BY day))/lag(count(1)) OVER(ORDER BY day))*100,2) percentage
    FROM DB_shop
    WHERE day BETWEEN cast(substring(regexp_replace(cast(date_add(to_date(from_unixtime(unix_timestamp(cast(${PERIOD} as string), 'yyyyMMdd'))),-1)  as string),'-',''),1,8) as int) AND cast(substring(regexp_replace(cast(to_date(from_unixtime(unix_timestamp(cast(${PERIOD} as string), 'yyyyMMdd')))  as string),'-',''),1,8) as int)
    GROUP BY day
    ORDER BY day DESC
    LIMIT 1
)x
ORDER BY PERIOD DESC)

SELECT concat("| ", PERIOD, " | ", TB_NAME, " | ", PERCENTAGE, " | ", STATUS, " |") change_in_percentage FROM trend;
  1. If the data is not null, it will come output:

change_in_percentage

| 20220805 | DB_shop | -5.7% | Normal |

  1. If the data is null, it will come output:

NULL

My question: How to handle null data to produce the desired output as follows:

change_in_percentage

| 20220807 | DB_shop | NULL | Data Not Found |

Thank you

wrap your case to coalesce with default value.

  coalesce(CASE
        WHEN percentage >= 20 THEN concat('Data increase ', cast(percentage AS STRING),'% from last day')
        WHEN percentage <= -20 THEN concat('Data drop ', cast(percentage AS STRING),'% from last day')
        WHEN percentage IS NULL THEN "Data Not Found"
        ELSE 'Normal'
    END, 'Data Not Found' )

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