PostgreSQL: Find shared beginning of string with SQL -


how can determine shared beginning of 2 or more strings using sql?

for example, have 3 uris:

'http://www.example.com/service/1' 'http://www.example.com/service/2' 'http://www.example.com/service/3' 

how can determine share 'http:://www.example.com/service/' using sql?

create aggregate function

create or replace function string_common_start (s text, t text) returns text $$ declare     sa char(1)[] = string_to_array(s, null);     ta char(1)[] = string_to_array(t, null);     output_s text = ''; begin      if s = t or t = '' or s = ''     return t;     end if;      in 1 .. least(length(s), length(t)) loop         if sa[i] = ta[i]                     output_s = output_s || sa[i];         else             exit;         end if;     end loop;      return output_s;  end; $$ language plpgsql strict;  create aggregate string_common_start (text) (     sfunc = string_common_start,     stype = text ); 

it not aggregate null values

select string_common_start(s) (values     ('http://www.example.com/service/1'),     ('http://www.example.com/service/2'),     ('http://www.example.com/service/3'),     (null) ) s(s);        string_common_start        ---------------------------------  http://www.example.com/service/ 

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -