简体   繁体   English

SQL 服务器:将连接表中的多行合并为一行?

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

I have an SQL query that looks like this.我有一个看起来像这样的 SQL 查询。

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).我正在尝试加入 Table2 所在的两个表(其中包含具有相同 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 SQL 服务器:将多行合并为一行

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.但我很难将其应用于上述查询。

Use a GROUP BY query with STRING_AGG :使用带有STRING_AGGGROUP BY查询:

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.我假设您使用的是 SQL Server 2017 或更高版本。 For earlier versions of SQL Server:对于 SQL 服务器的早期版本:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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