我有列 'Age' (Varchar) 如何选择查询并将其转换为 (float)
Pet_Name Age(varchar)
John 2 年 6 个月。
安妮 3 岁零 6 个月。
输出:
Pet_Name Age(float/double)
John 2.5
Anne 3.5
我的问题是输入不遵循特定的日期/年龄格式,而是作为字符串输入的。
假设年龄列总是有两个数字,我在 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 |
+--------------------+
注意:以上答案仅适用于年龄列中有两个数字的情况。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句