在SQL Server 2012表中,我想从两列中获取所有行,并将它们转换为一行,仍然是两列,但每列都以逗号分隔。
例如
Customerid | FacilityId
-----------------------------
1 5678
2 9101
5 6543
之后我觉得结果就像这样
Customerid | FacilityId
-----------------------------
1,2,5 5678,9101,6543
答案 0 :(得分:4)
您可以像SQL Fiddle
一样使用FOR XML
<强>查询强>
SELECT STUFF((
SELECT ',' + CONVERT(VARCHAR(10),Customerid)
FROM Customer
FOR XML PATH('')),1,1,'') as Customerid,
STUFF((
SELECT ',' + CONVERT(VARCHAR(10),FacilityId)
FROM Customer
FOR XML PATH('')),1,1,'') as FacilityId
<强>输出强>
Customerid FacilityId
1,2,5 5678,9101,6543
修改强>
您甚至可以使用变量将csv连接在一起,这不需要像FOR XML
这样的2个表扫描,但是当您在同一查询中使用ORDER BY
或其他函数时可能会遇到问题。
由于您只有3-4行,我建议使用FOR XML
方法
DECLARE @Customerid VARCHAR(MAX) = '',@FacilityId VARCHAR(MAX) = ''
SELECT
@Customerid += ',' + CONVERT(VARCHAR(10),Customerid),
@FacilityId += ',' + CONVERT(VARCHAR(10),FacilityId)
FROM Customer
SELECT STUFF(@Customerid,1,1,'') as Customerid, STUFF(@FacilityId,1,1,'') as FacilityId
答案 1 :(得分:3)
使用CONCAT这是一种简单快捷的方法,它可以在sqlserver 2012中使用:
DECLARE @t table(Customerid int, FacilityId int)
INSERT @t values(1,5678),(2,9101),(5,6543)
DECLARE @x1 varchar(max), @x2 varchar(max)
SELECT
@x1 = concat(@x1 + ',', Customerid),
@x2 = concat(@x2 + ',', FacilityId)
FROM @t
SELECT @x1, @x2
答案 2 :(得分:0)
你可以这样做:
SELECT * FROM
(SELECT Customerid = STUFF((
SELECT ',' + CAST(md.Customerid as varchar(max))
FROM dbo.TableName md
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, ''),
Facilityid=STUFF((
SELECT ',' + CAST(md.Facilityid as varchar(max))
FROM dbo.TableName md
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM dbo.TableName m
JOIN dbo.TableName s ON s.customerid = m.customerid AND s.facilityid=m.facilityid) as Tbl
GROUP BY customerid,facilityid
结果:
Customerid Facilityid
--------------------------
1,2,5 5678,9101,6543
中的示例结果
答案 3 :(得分:0)
在SQL SERVER中使用FOR XML PATH
SELECT (SELECT CAST(Customerid AS VARCHAR) + ',' from
Table for XML PATH(''), type).value('.', 'varchar(max)') AS Customerid,
(SELECT CAST(FacilityId AS VARCHAR) + ',' from
Table for XML PATH(''), type).value('.', 'varchar(max)') AS FacilityId
答案 4 :(得分:0)
您可以STUFF
使用FOR XML
来实现此目的:
CREATE TABLE #tmpDemo (CustomerId INT, FacilityId INT)
INSERT INTO #tmpDemo VALUES (1, 5678), (2, 9101), (5, 6543)
SELECT DISTINCT
STUFF((
SELECT ',' + CAST(T.CustomerId AS VARCHAR)
FROM #tmpDemo T
FOR XML PATH('')), 1, 1, '') as CustomerId,
STUFF((
SELECT ',' + CAST(T.FacilityId AS VARCHAR)
FROM #tmpDemo T
FOR XML PATH('')), 1, 1, '') as FacilityId
FROM #tmpDemo m
DROP TABLE #tmpDemo
这可能会导致大型数据集出现严重的性能问题,但我从上面的评论中注意到,您只会拥有少量行。
答案 5 :(得分:0)
使用COALESCE
DECLARE @Names VARCHAR(8000)
DECLARE @id VARCHAR(8000)
SELECT @id = COALESCE(@id + ', ', '') + CAST(col1 AS VARCHAR),@Names = COALESCE(@Names + ', ', '') + col2
FROM tab1
select @id,@Names
<强> SQLFiddle Demo 强>