【问题标题】:regex: Find next or previous letter in the alphabet正则表达式:在字母表中查找下一个或上一个字母
【发布时间】:2021-08-19 07:53:56
【问题描述】:

我有一个 Oracle SQl 表,它有 2 个列,value 和 positionid,value 从 -10 到 10,positionid 从 A01 到 K25。

我需要找出哪个相邻位置的差值大于或等于 5。邻居位置是由它的 positionid 根据字母和数字顺序确定的,如下表所示:,B02 将作为邻居位置 A01、A02、A03、B01、B03、C01、C02 和 C03

| A01 | A02 | A03 | A04 |
| B01 | B02 | B03 | B04 |
| C01 | C02 | C03 | C04 |
| D01 | D02 | D03 | D04 |

例如:

  • 位置 B02 的值为 5 和位置 C03 的值为 -5 匹配该条件,因为它们是邻居并且值差大于 5。
  • 值为 5 的位置 B02 和值为 4 的位置 C03不匹配,因为它们是邻居,但值差小于 5。
  • 位置 A20 的值为 5 和位置 E05 的值为 -5不匹配条件,因为它们不是邻居。

对于 SQL 查询或至少一个正则表达式来查找这些邻居位置有什么建议吗?

value positionid
2 A01
-4 A02
7 A03
. .
4 C12
2 C13
0 C14

想要的输出可以很简单,只需要两个 positionid 和两个值。

【问题讨论】:

  • 您使用的是哪个 dbms? (许多产品都有自己的正则表达式版本。)
  • 向我们展示一些示例表数据和预期结果 - 全部为格式化文本(不是图像)。minimal reproducible example
  • 是什么决定了两个Pos的关系?为什么 B02 和 C03 是邻居?
  • 仍然没有具有期望输出的代表性示例

标签: sql regex oracle


【解决方案1】:

您可以使用如下查询。 where 子句中有 cmets 解释每个部分在做什么。下面的示例是搜索positionid C03,但您可以更改该值以检查不同的位置。

此外,您可以从 search_pos 公用表表达式中完全删除 where 子句,并将列添加到正在选择的列列表中,并且能够查看与您描述的条件匹配的所有位置/值组合。

WITH
    search_pos
    AS
        (SELECT VALUE, positionid
           FROM positions
          WHERE positionid = 'C03')
SELECT p.VALUE, p.positionid
  FROM positions p, search_pos s
 WHERE --Check to make sure the 1st character (Letter) is the same or a neighboring letter
           SUBSTR (p.positionid, 1, 1) IN
               (SUBSTR (s.positionid, 1, 1),
                CHR (ASCII (SUBSTR (s.positionid, 1, 1)) - 1),
                CHR (ASCII (SUBSTR (s.positionid, 1, 1)) + 1))
       --Check to make sure the 2nd and 3rd characters (numeric) is the same or a neighboring number
       AND TO_NUMBER (SUBSTR (p.positionid, 2, 2)) IN
               (TO_NUMBER (SUBSTR (s.positionid, 2, 2)),
                TO_NUMBER (SUBSTR (s.positionid, 2, 2)) - 1,
                TO_NUMBER (SUBSTR (s.positionid, 2, 2)) + 1)
       --Exclude the position currently being searched for
       AND p.positionid <> s.positionid
       --Check that the value has a 5 or greater difference from the value of the position being searched
       AND (p.VALUE >= s.VALUE + 5 OR p.VALUE <= s.VALUE - 5);

【讨论】:

    猜你喜欢
    • 2012-02-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多