Padding Leading Zero's based on Column Length In Hive

601 views Asked by At

I have one table in Hive.

Vari_Length    Fixed_Length
12345            12345
 1234            12345
  123            12345
   12            12345
    1            12345

Here I am generating one new column by comparing the length of both the column.

i.e.

Vari_Length    Fixed_Length     newcolumn

12345               12345        12345
 1234               12345        01234
  123               12345        00123
   12               12345        00012
    1               12345        00001

here if Vari_Length length is less then the length of Fixed_Length then I am padding leading zeroes in Vari_Length values and generating the newColumn.

Here Fixed_Length length is fixed every-time it will be 5 but Vari_Length length is not fixed.

I am using below query to generate the output.

select
case when 
length(Vari_Length)='5'
THEN Fixed_Length
when length(Vari_Length)='4'
THEN concate('0',Fixed_Length)
when length(Vari_Length)='3'
then concate('00',Fixed_Length)
when length(Vari_Length)='2'
then concate('000',Fixed_Length)
when length(Vari_Length)='1'
then concate('0000',Fixed_Length)
end as newcolumn from mytable

But here multiple case statement are there, So I am trying to optimize the query and wondering if is there any other way to achive the same using hive function without using multiple case statements.

Kindly Suggest.

1

There are 1 answers

0
Rahul Patidar On

It worked Now.

select lpad(Fixed_Length,length(Vari_Length),0) as newcolumn from mytable;