Convert Varchar to Float/double

2019-08-18 05:30发布

问题:

I have column 'Age' (Varchar) How can I select query and convert it to (float)

Pet_Name         Age(varchar)
John                  2 years 6 months.
Anne                  3 years and 6 months.

output:
Pet_Name         Age(float/double)
John                  2.5
Anne                 3.5

my problem is that the inputs does not follow a specific date/age format and was entered as string.

回答1:

Assuming the age column always has two numbers, I have used REGEXP_SUBSTR function in Redshift to write below answer:

create temp table pets (petname varchar(10), age varchar(20));

insert into pets values ('john','2 years 6 mnths');
insert into pets values ('anne','3 Years and 4 months');
insert into pets values ('buddy','4 yrs and 3 Mnths');
insert into pets values ('tommy','9 Years and 5 mnths');
insert into pets values ('alex','5 YEARS and 12 mnts');
insert into pets values ('bob','0 year and 7 Mnts');
insert into pets values ('danny','10 years 11 mnths');
insert into pets values ('sunny','81 years 10 mnths');


select petname,(REGEXP_SUBSTR(AGE,'[0-9]|[0-9][0-9]',1))::integer+(REGEXP_SUBSTR(AGE,'[0-9]|[0-9][0-9]',3))/12 as age from pets;

+--------------------+
|petname   | age     | 
+--------------------+
|john      |2.5000   |
|sunny     |81.8333  |
|danny     |10.9166  |
|anne      |3.3333   |
|alex      |6.0000   |
|tommy     |9.4166   |
|bob       |0.5833   |
|buddy     |4.2500   |
+--------------------+

Note: The above answer works only when there are two numbers in the age column.