Home > Software design >  Return all substring values from a string column when contains a small list of substring
Return all substring values from a string column when contains a small list of substring

Time:01-28

I have a table of prescriptions that may contains multiple medicines in the same column. I'm looking to return in a query only when some medicines (a list of 3 medicines) are present, only one or any or all of then. As an example, looking to get when there is Medicine A, Medicine B and Medicine C. This field may contains some notes about the medicine as well.

Input:

*column A*
Medicine A 
Medicine B and Medicine D
2 x day Medicine A and 1 shot of Medicine C
Medicine E and Medicine D
Medicine D , Medicine A and Medicine B
Medicine E , Medicine C and Medicine A

Expected Output:

*column A*
Medicine A 
Medicine B
Medicine A Medicine C

Medicine A Medicine B
Medicine C Medicine A

I'm working with Postgres 13.7. Any advice is appreciated! Thanks

I tried to work with case when. However if I needed to include another Medicine in the list would have expanded a lot.

CodePudding user response:

You can use the regexp_matches function to get all of the required matches, then use the string_agg function to group the resulting matches in one row.

select columnA, string_agg(translate(m::text, '{}"',''), ' ') matches
from
(
  select columnA , 
     regexp_matches(columnA, 'Medicine [ABC]', 'g') m
  from table_name
) T
group by columnA

See demo

  • Related