SQL Server: Combine multiple rows into one row from a join table?

心已入冬 提交于 2021-02-08 11:42:09

问题


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.


回答1:


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;


来源:https://stackoverflow.com/questions/58374177/sql-server-combine-multiple-rows-into-one-row-from-a-join-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!