在具有相同 ID SQL Server 2005 的不同行中连接列
Concat columns in different rows with same ID SQL Server 2005
我希望在每一行中连接一个包含文本输入的列....
我正在使用 SQL Server 2005
行看起来像这样
Number Date Update Time description
------ ----- ----------- -------------
0123 01/01/2015 01/07/2015 Hello, I want to
0123 01/01/2015 01/01/2015 Concat these columns
希望这很容易,我只是个傻瓜
您可以使用这种方法:
SELECT A.Number, MAX(A.[Date]) AS [Date], MAX(A.[Update Time]) AS [Update Time]
, STUFF((SELECT ' ' + B.description AS [text()]
FROM table1 B
WHERE A.Number = B.Number
FOR XML PATH('')), 1, 1, '' ) AS Description
FROM table1 A
GROUP BY A.Number
因为您处理的是自由格式文本,我认为最好将 XML 显式转换回字符数据类型:
SELECT t.Number,
STUFF((SELECT ' ' + cast(t2.description AS nvarchar(max) )
FROM <tablen> t2
WHERE t2.Number = t.Number
FOR XML PATH(''), TYPE
).VALUE('.', 'nvarchar(max)'
), 1, 1, '' ) AS Description
FROM <table> t
GROUP BY t.Number;
这可以防止 &
、<
和 >
等字符出现问题。
我希望在每一行中连接一个包含文本输入的列....
我正在使用 SQL Server 2005
行看起来像这样
Number Date Update Time description
------ ----- ----------- -------------
0123 01/01/2015 01/07/2015 Hello, I want to
0123 01/01/2015 01/01/2015 Concat these columns
希望这很容易,我只是个傻瓜
您可以使用这种方法:
SELECT A.Number, MAX(A.[Date]) AS [Date], MAX(A.[Update Time]) AS [Update Time]
, STUFF((SELECT ' ' + B.description AS [text()]
FROM table1 B
WHERE A.Number = B.Number
FOR XML PATH('')), 1, 1, '' ) AS Description
FROM table1 A
GROUP BY A.Number
因为您处理的是自由格式文本,我认为最好将 XML 显式转换回字符数据类型:
SELECT t.Number,
STUFF((SELECT ' ' + cast(t2.description AS nvarchar(max) )
FROM <tablen> t2
WHERE t2.Number = t.Number
FOR XML PATH(''), TYPE
).VALUE('.', 'nvarchar(max)'
), 1, 1, '' ) AS Description
FROM <table> t
GROUP BY t.Number;
这可以防止 &
、<
和 >
等字符出现问题。