我的表TEST
包含以下行:
test | 1
test | 2
test | 3
我如何查询它以获得以下结果?
test | 1 - 2 - 3
答案 0 :(得分:1)
您可以使用Coalesce功能对列表中的数字进行排序。希望这会给你一个开始:
Declare @T as Table (Col1 varchar(35), Col2 int)
Insert into @T(Col1, Col2)
Select 'Test', 1
Insert into @T(Col1, Col2)
Select 'Test', 2
Insert into @T(Col1, Col2)
Select 'Test', 3
DECLARE @X varchar(200)
SELECT @X = COALESCE(@X + ' - ', '') + Cast(Col2 as varchar(5))
From @T
Select @X
答案 1 :(得分:1)
尝试:
SELECT x.column1,
STUFF(SELECT ' - ' + t.column2
FROM TEST t
WHERE t.column1 = x.column1
ORDER BY t.column1
FOR XML PATH(''), 1, 1, '')
FROM TEST x
参考:STUFF