gpt4 book ai didi

oracle - 将 "regexp_substr"(Oracle) 转换为 PostgreSQL

转载 作者:行者123 更新时间:2023-11-29 13:00:25 31 4
gpt4 key购买 nike

我在 Oracle SQL 中有查询:

       select town_name, 
regexp_substr(town_name, '[^A,]+', 1, 1) as c1,
regexp_substr(town_name, '[^A,]+', 1, 2) as c2,
regexp_substr(town_name, '[^A,]+', 1, rownum) as c_rownum,
rownum
from epr_towns

结果的前两行是:

VALGANNA        V   LG  V   1
VARANO BORGHI V R R 2

我需要在 PostgreSQL 上获得相同的结果(对于 regexp_substr(town_name, '[^A,]+', 1, rownum) 作为 c_rownum 的行),但我不需要知识。你可以帮帮我吗?谢谢。

最佳答案

这里确实有两个不同的问题

  • 替换rownum
  • 用 regexp_matches 替换 regexp_substr

要解决 rownum,请使用 CTE(WITH 子句)将类似 rownum 的列添加到您的基础表。

regexp_matches 的工作方式与 Oracle regexp_substr 略有不同。 Oracle regexp_substr 将第 n 个匹配项作为参数,而 PostgreSQL regexp_matches 将返回所有 个匹配项作为表值函数。因此,您必须将调用包装在具有限制/偏移量的子查询中,以提取第 n 个匹配项。此外,regexp_substr 返回的行是数组,因此假设您的正则表达式中没有带括号的表达式,您需要索引/取消引用数组中的第一项。

最终结果是这样的:

http://sqlfiddle.com/#!17/865ee/7

 with epr_towns_rn as (
select town_name,
row_number() over(order by town_name) as rn
from epr_towns
)
select town_name,
(select (regexp_matches(town_name, '[^A,]+', 'g'))[1] offset 0 limit 1) as c1,
(select (regexp_matches(town_name, '[^A,]+', 'g'))[1] offset 1 limit 1) as c2,
(select (regexp_matches(town_name, '[^A,]+', 'g'))[1] offset rn-1 limit 1)
as c_rownum,
rn
from epr_towns_rn;

如果您只想要第一个匹配项,您可以省略“g”参数并省略子查询的限制/偏移量,但您仍然需要子查询包装器以防没有匹配项,以模拟 regexp_substr 在没有匹配项时返回 null匹配。

关于oracle - 将 "regexp_substr"(Oracle) 转换为 PostgreSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32067906/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com