无论数字出现如何,在PostgreSQL中获取数字部分后跟1位小数

时间:2018-03-29 12:18:10

标签: sql postgresql

我的数据是这样的

server      version
Server 1    5.1.42
Server 2    MySQL 5.7.16
Server 3    mysql-5.0.67-linux
Server 4    MARIADB - 10.2.9-MariaDB-log
Server 5    5.6.12-community-log
Server 6    mysql-advanced-5.6.12
Server 7    PERCONA - 5.7.19-17-log

我想要的输出是

Server 1    5.1
Server 2    5.7
Server 3    5.0
Server 4    10.2
Server 5    5.6
Server 6    5.6
Server 7    5.7

5 个答案:

答案 0 :(得分:2)

如果保留版本号的所有数字(而不是前两个),事情会变得容易多了:

select server, 
       regexp_replace(version, '[^0-9.]', '', 'g') as version_string
from data;

如果您还想按这些数字正确排序,请将结果转换为整数数组并按以下顺序排序:

select server, 
       regexp_replace(version, '[^0-9.]', '', 'g') as version_string
from data
order by string_to_array(regexp_replace(version, '[^0-9.]', '', 'g'), '.')::int[];

答案 1 :(得分:1)

select server,(regexp_matches(version, '[0-9]+\.?[0-9]*')) as Version
from Table1

OR

select server,(regexp_matches(version, '\d+\.?\d*')) as Version
from Table1

输出

server      version
Server 1    5.1
Server 2    5.7
Server 3    5.0
Server 4    10.2
Server 5    5.6
Server 6    5.6
Server 7    5.7

演示

  

http://sqlfiddle.com/#!17/121e2/12

答案 2 :(得分:1)

您可以使用substring(string from pattern)函数,其中 pattern 将是POSIX正则表达式[0-9]+\.[0-9]{1}

<强>解决方案

select server, substring(version from '[0-9]+\.[0-9]{1}') as version
from yourtable;

示例

select substring('MARIADB - 10.2.9-MariaDB-log' from '[0-9]+\.[0-9]{1}') AS output;

 output
---------
 10.2

正则表达式解释:

  • [0-9]+匹配同等数量或多个数字
  • 的字符
  • \.匹配点
  • [0-9]{1}同样匹配一个号码

答案 3 :(得分:1)

考虑@Damien's comment,我建议:

SELECT server
     , substring(version, '\d+(?:\.\d)?')  AS u_ask
     , substring(version, '\d+(?:\.\d+)?') AS u_might_need
FROM   tbl;
带有扩展测试用例的

SQL Fiddle

\d ..班级简写为数字
+ ..发生1次或更多次 ? .. 0或1次出现
(?:re) .. “non-capturing” set of parentheses

答案 4 :(得分:0)

我也尝试过这样的工作

SELECT "server", 
CONCAT(substring(version FROM '[0-9]+'),'.', split_part(version, '.', 2)) as newversion,
 FROM "tablename";