【问题标题】:Convert Varchar to Float/double将 Varchar 转换为浮点数/双精度
【发布时间】:2018-04-26 19:29:53
【问题描述】:

我有“年龄”列 (Varchar) 如何选择查询并将其转换为 (float)

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

输出:
宠物名         年龄(浮动/双倍)
约翰                 2.5
安妮                3.5

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

【问题讨论】:

  • 总是“n年n个月。”可能是“23 yrs”“6 mnths”吗?总是英文吗?你需要更多的例子。每个例外都会使这变得更加困难,即使是空格的数量也可能会有所不同。 & 如果您打算解决此问题,我希望新的“年龄”列是小数,而不是字符串。
  • 2.5 不是整数。它是浮动的或双重的
  • 把题目改成你的问题,整数不能有小数部分
  • 我将上述问题从 int 更新为 float。
  • @Used_By_Already 我的问题是输入不遵循特定的日期/年龄格式,而是作为字符串输入的。

标签: sql converter amazon-redshift


【解决方案1】:

假设年龄列总是有两个数字,我在 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 列中有两个数字时有效。

【讨论】:

  • 如果输入只是3 months怎么办?
  • @JohnRotenstein hmmm .. 正如我在答案中提到的,这仅在列有两个数字时才有效。我现在用注释更新了答案。
猜你喜欢
  • 2015-06-12
  • 1970-01-01
  • 1970-01-01
  • 2018-08-09
  • 2011-11-22
  • 1970-01-01
  • 1970-01-01
  • 2016-02-26
  • 1970-01-01
相关资源
最近更新 更多