首页 文章

从varchar列中提取字母数字值

提问于
浏览
-1

我有一个表,其中包含一个具有 alphanumeric 值的列,该列存储为字符串 . 我在该列中有多个值,其值包括 F473700Y778PP0098XXYYYZ 等 .

我想 extract values starting with a series of F and must have numeric values in that row. 字母数字列是具有唯一值的唯一列,但其余列在我的表中包含重复值 .

此外,一旦提取了这些值,我想从重复行中选取 max value ,例如:

假设我将 F4737F4700 作为唯一的字母数字行,则必须从中提取 F4737 .

我写了这样的查询但是没有从这个查询中提取数值:

select max(Alplanumeric) 
from Customers 
where Alplanumeric '%[F0-9]%

要么

select max(Alplanumeric) 
from Customers 
where Alplanumeric like '%[0-9]%' 
and Alplanumeric like 'F%'**

我运行上面的查询,但如果我从上面的查询中删除数字部分,我只得到F系列 . 如何提取F起始系列以及该行中包含的数值?

1 回答

  • 0

    走出困境,你可能正在寻找这样的查询:

    SELECT *, substring(alphanumeric, '^F(\d+)')::int AS nr
    FROM   customers 
    WHERE  alphanumeric ~ '^F\d+' 
    ORDER  BY nr DESC NULLS LAST
            , alphanumeric
    LIMIT  1;
    

    WHERE 条件是正则表达式匹配,表达式锚定到start,因此它可以使用索引 . 理想的情况是:

    CREATE INDEX customers_alphanumeric_pattern_ops_idx ON customers
    (alphanumeric text_pattern_ops);
    

    这将返回 alphanumeric 中以'F'开头,后跟一个或多个数字的行中具有最高(提取)数值的一行 .

    关于指数:

    关于模式匹配:


    理想情况下,您应该在 separate 列中存储前导文本和以下数值,以提高效率 . 您不一定需要更多像已建议的表 .

相关问题