将 Varchar 转换为 Float/double

Convert Varchar to Float/double

我有列 'Age' (Varchar) 我如何 select 查询并将其转换为 (float)

Pet_Name 年龄(varchar)
约翰 2 年 6 个月。
安妮 3 岁零 6 个月。

输出:
Pet_Name 年龄(float/double)
约翰 2.5
安妮 3.5

我的问题是输入不遵循特定的 date/age 格式,而是作为字符串输入的。

假设年龄列总是有两个数字,我在Redshift中使用REGEXP_SUBSTR函数写下答案:

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   |
+--------------------+

注意:只有当年龄列中有两个数字时,以上答案才有效。