Search code examples
sqlstringcoalesce

Turning one column into a string in SQL


I have a table in SQL that look like this:

img

The issue is that I would like it to be displayed in this fashion:

Medication Review | Allergies, CAM, Diet Supp, 

Having one presenting problem and all of the secondary problems in a single row instead of the way it is now.

Any help would be awesome! Thanks!


Solution

  • If you are using SQL Server, you can do this:

    SELECT DISTINCT t1.presenting_problem,
      STUFF(
             (SELECT ', ' + t2.secondary_problem
              FROM tableName t2
              where t1.presenting_problem = t1.presenting_problem
              FOR XML PATH (''))
              , 1, 1, '')  AS secondary_problems
    from tableName t1;