将Varchar转换为Float / double

时间:2017-11-14 00:33:14

标签: sql converter amazon-redshift

我有专栏'Age'(Varchar) 如何选择查询并将其转换为(float)

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

输出:
Pet_Name 年龄(浮动/双倍)
约翰的 2.5
安3.5

我的问题是输入没有遵循特定的日期/年龄格式,而是以字符串形式输入。

1 个答案:

答案 0 :(得分:2)

假设年龄栏总是有两个数字,我在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   |
+--------------------+

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