实现此结果的 SQL Server 代码是什么:
SO number Line number
123 6
123 189
456 34
需要输出:
SO number Line number
123 6,189
456 34
实现此结果的 SQL Server 代码是什么:
SO number Line number
123 6
123 189
456 34
需要输出:
SO number Line number
123 6,189
456 34
尝试这个 :-
CREATE TABLE #Sample ([SO Number] INT, [Line Number] INT)
INSERT INTO #Sample ([SO Number],[Line Number]) VALUES (123,6)
INSERT INTO #Sample ([SO Number],[Line Number]) VALUES (123,189)
INSERT INTO #Sample ([SO Number],[Line Number]) VALUES (456,34)
SELECT ID,
STUFF((
SELECT ', ' + cast([Line Number] as varchar(max) )
FROM #Sample
WHERE ([SO Number] = a.[SO Number])
FOR XML PATH (''))
,1,2,'') AS b
FROM #Sample a
GROUP BY [SO Number]
编辑 :
XML PATH (''):Is used to retrieve the column values seperated by comma
Ex:- ,6,189,34
STUFF:用于将一个字符串插入到另一个字符串中。表达式为
STUFF ( character_expression , start , length ,character_expression )
起始长度为 1,因为我们必须替换 XML PATH 创建的第一个逗号。''
插入的空间长度为 1
因此,即使您有 20K 行,表达式仍将与 1,2 用于插入空间相同
DECLARE @Sample Table([SO Number] INT, [Line Number] INT)
INSERT INTO @Sample ([SO Number],[Line Number]) VALUES (123,6)
INSERT INTO @Sample ([SO Number],[Line Number]) VALUES (123,189)
INSERT INTO @Sample ([SO Number],[Line Number]) VALUES (456,34)
select * from @Sample
select [SO Number],STUFF((select ','+cast([Line Number] as varchar(100)) from @Sample s1 where s1.[SO Number] =s.[SO Number] FOR XML path('')),1,1,'' ) as [Line Number] from @Sample s
group by [SO Number]