Convert Varchar to Float/double

送分小仙女□ 提交于 2020-01-25 07:13:08

问题


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.



来源:https://stackoverflow.com/questions/47275801/convert-varchar-to-float-double

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