如何在T_SQL中实现多行文字的连接

问题描述 投票:0回答:2

我在SQL Server中使用T-SQL处理下面的问题,遇到了一点障碍。

我希望将多行文本连成一行(下面的文本列),依据是 personID.

例如,如果我的原始数据是。

PersonID   Text                     Line Number
-----------------------------------------------
A          The woman went to        1
A          the zoo,                 2
A          then went home.          3
B          A man went to            1
B          the aquarium,            2
B          spoke to                 3 
B          the fish,                4
B          then got an ice cream.   5
C          People love              1
C          football.                2

我需要的输出是:

PersonID   Text                                                                        
Line Number
-------------------------------------------------------------------------------
A          The woman went to    the zoo,  then went home.                              1
B          A man went to the aquarium, spoke to the fish,   then got an ice cream.     1
C          People love  football.                                                      1

原始数据的文本行数因人而异,我找不到一个解决方案来解决这个问题(例如:A人=3,B人=5,C人=2)。

任何帮助将是非常感激的

sql sql-server tsql concat window-functions
2个回答
2
投票

如果你有SQL Server 2017或更高版本,你可以使用STRING_AGG()如下。

CREATE TABLE #Person (PersonID varchar(2), PersonText varchar(100), Line_Number int)

INSERT INTO #Person VALUES('A','The woman went to',1)
INSERT INTO #Person VALUES('A','the zoo,',2)
INSERT INTO #Person VALUES('A','then went home.',3)
INSERT INTO #Person VALUES('B','A man went to',1)
INSERT INTO #Person VALUES('B','the aquarium,', 2)
INSERT INTO #Person VALUES('B','spoke to',3 )
INSERT INTO #Person VALUES('B','the fish,',4)
INSERT INTO #Person VALUES('B','then got an ice cream.',5)
INSERT INTO #Person VALUES('C','People love',1)
INSERT INTO #Person VALUES('C','football.',2)

select PersonID, STRING_AGG(PersonText, ' ') PersonText
from #Person
GROUP BY PersonID

如果不是的话使用FOR XML也可以。

SELECT PersonID, 
    (SELECT PersonText + ' ' 
            FROM #Person t1 
            WHERE t1.PersonID = t2.PersonID ORDER BY Line_Number FOR XML PATH('') ) PersonText
FROM  #Person t2
GROUP BY PersonID

1
投票
SELECT DISTINCT
    t.PersonID,
    (
    SELECT
        tt.[Text] + ' '
    FROM
        my_table tt
    WHERE
        t.PersonID = tt.PersonID
    ORDER BY
        tt.[Line Number]
    FOR XML PATH('')
    ) AS text_out
FROM
    my_table t
© www.soinside.com 2019 - 2024. All rights reserved.