简体   繁体   中英

Return all substring values from a string column when contains a small list of substring

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM