Need to combine two columns into one column, and then combine multiple rows into one row from that new column.

Mathew 20 Reputation points
2024-07-09T15:58:21.0966667+00:00

I have combined two columns into one column using CONCAT, and now need to combine multiple rows from that new column into one row. Here is my sample table:

SELECT bac.BacteriaSID

       , bac.AntibioticValue

       , bac.Antibiotic

       , CONCAT (AntibioticValue, ' ',Antibiotic) AS ABX_sensitivity

 FROM Bacteria.Antibiotic AS bac

 WHERE bac.Hospital = 123

I have combined 'AntibioticValue' and 'Antibiotic' into one column (ABX_sensitivity) using the CONCAT function (also, I'm unsure if this is the correct avenue to take). It returns correctly, as noted in the image below. Now I need to combine all rows with the same "BacteriaSID" into one row. I have outlined the rows that need to be one row, according to the common BacteriaSID. How do I write this expression? (I've included the WHERE statement because I need to see how that fits into the total SQL pull). I am using SSMS.

User's image

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,788 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 117.3K Reputation points
    2024-07-09T16:32:40.7533333+00:00

    Try this query:

    select BacteriaSID, string_agg(concat(AntibioticValue, ' ', Antibiotic), ', ') as ABX_sensitivities
    from Bacteria.Antibiotic
    where Hospital = 123
    group by BacteriaSID
    order by BacteriaSID
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.