1

I have an SQL query that looks like this.

SELECT ID, Data1, DataFromTable2
FROM Table1
LEFT JOIN Table2 on Table1.ID = Table2.ID
WHERE ID = 1

I'm trying to join the two tables where Table2 (which contains multiple rows with the same ID). And I want to the multiple rows into one row.

I found a post here that combines the multiple rows into one. SQL Server: combining multiple rows into one row

DECLARE @combinedString VARCHAR(MAX)
SELECT @combinedString = COALESCE(@combinedString + ', ', '') + stringvalue
FROM jira.customfieldValue
WHERE customfield = 12534
AND ISSUE = 19602

SELECT @combinedString as StringValue 

But I'm having a hard time applying it to the above query.

bigbryan
  • 411
  • 6
  • 19
  • 36

1 Answers1

3

Use a GROUP BY query with STRING_AGG:

SELECT
    t1.ID,
    t1.Data1,
    STRING_AGG(t2.DataFromTable2, ',') AS data
FROM Table1 t1
LEFT JOIN Table2 t2
    ON t1.ID = t2.ID
GROUP BY
    t1.ID,
    t1.Data1
WHERE
    t1.ID = 1;

I am assuming you are using SQL Server 2017 or later. For earlier versions of SQL Server:

SELECT
    t1.ID,
    t1.Data1,
    data = STUFF((
      SELECT ',' + t2.DataFromTable2
      FROM Table2 t2
      WHERE t2.ID = t1.ID
      FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM Table1 t1;
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360