Oracle select mutual sub string from different rows

[亡魂溺海] 提交于 2020-07-08 00:48:43

问题


I would like to return new table in ORACLE where all the rows that have same values in 'col' column group together and the 'description' column will contain only the mutual sub strings when the different characters will replaced by '...'

How can I do that? May I get your help please?

Example:

col description
1   Today is a good day
1   Today is perfect day
2   Hello world
2   Hello I'm here
3   Hi

Result:

col description
1   Today is …
2   Hello…
3   Hi

thanks!


回答1:


In order to achieve what you want, first you will need to know how common string start can be found in Oracle:

with rws as ( 
  -- generate rows up to the length of the longest string 
  select rownum r from dual 
  connect by level <= (select max(length(str)) from strings) 
) 
select distinct s  
from ( 
  select str, max(subp) s  
  from ( 
    select str,  
           substr(str, 1, rws.r) subp 
    from   strings s1 
    cross join rws 
    where  r < length(str) 
    and    exists ( 
      -- check whether there's another string matching the first N chars 
      select * from strings s2 
      where  s1.str <> s2.str 
      and    substr(s1.str, 1, rws.r) = substr(s2.str, 1, rws.r) 
    ) 
  )  
  group by str 
)

Taken from https://livesql.oracle.com/apex/livesql/file/content_CC83ZWPCPESEDTADIFOSB1EXI.html

Of course, you will need to apply this to your table. Differences:

  • you will need to use your columns
  • you will need to group by col


来源:https://stackoverflow.com/questions/62756449/oracle-select-mutual-sub-string-from-different-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!