3

I have table 'A' in PostgreSQL database:

name     fullname
A         A,I,A
B         B,B,S,B
D         D,D,S,E,D
E         E,E,D,G,E
F         F,F,G,F
G         G,E,G,F,G,H,N,G

How receive table 'B' with column 'correctname' (fullname) where in each row no matching substrings from 'name' field:

name  correctname
A      I
B      S
D      S,E
E      D,G
F      G
G      E,F,H,N

Sample of data:

CREATE TABLE test(name TEXT, fullname TEXT);

INSERT INTO test(name, fullname) VALUES('A','A,I,A');
INSERT INTO test(name, fullname) VALUES('B','B,B,S,B');
INSERT INTO test(name, fullname) VALUES('D','D,D,S,E,D');
INSERT INTO test(name, fullname) VALUES('E','E,E,D,G,E');
INSERT INTO test(name, fullname) VALUES('F','F,F,G,F');
INSERT INTO test(name, fullname) VALUES('G','G,E,G,F,G,H,N,G');

Thanks!

1
  • I think it is more a job for the application itself than the sql server. Commented Aug 23, 2013 at 12:05

1 Answer 1

5

Solution:

SELECT 
name
,trim(
REGEXP_REPLACE(fullname,'(,|^)('||name||'(,|$))+',',','cg')
,',')
FROM data;

or

SELECT REPLACE(REPLACE(fullname, name||',', ''), ','||name, '') FROM test;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.