首页 > 解决方案 > 如何在字符序列正则表达式SQL中找到相同的两位数字

问题描述

我想打印出在 SQL 中至少重复两个数字的字符串

EX

11-22-33
11-22-44
22-22-33
55-22-33
11-66-33
11-88-33
33-88-33
77-77-22

输出 :

22-22-33
77-77-22
33-88-33

但我不知道如何编写一个对我有帮助的正则表达式

标签: sqlstringoracle

解决方案


对于这种固定格式NN-NN-NN,您可以只使用字符串函数并测试三种可能的组合:

select *
from mytable
where substr(val, 1, 2) = substr(val, 3, 2) 
   or substr(val, 1, 2) = substr(val, 5, 2) 
   or substr(val, 3, 2) = substr(val, 5, 2) 

我们可以花点心思,使用横向连接代替重复or条件。如果您有 3 个以上的部分,这将更好地扩展(组合的数量迅速增加,这使得or解决方案不太方便):

select t.*
from mytable t
cross apply (
    select count(distinct part) cnt_distinct_part
    from (
        select substr(t.val, 1, 2) part
        union all select substr(t.val, 3, 2)
        union all select substr(t.val, 5, 2)
    ) x
) x
where x.cnt_distinct_part < 3

推荐阅读