SQL 服务器合并数据集
SQL Server Coalesce data set
我有一个查询 return 是一个如下所示的数据集:
Region Name
-------------------------------------------------------------
Canada Jim
Canada Michael
Canada Andy
Mexico Jim
Mexico Michael
Mexico Kevin
但我想 return 改成这样:
Region Name
-------------------------------------------------------------
Canada, Mexico Jim
Canada, Mexico Michael
Canada Andy
Mexico Kevin
当名称相等时,我的游标查询尝试合并区域名称
OPEN RegionCursor
FETCH NEXT
FROM RegionCursor
INTO @regionNext
,@NameNext
SET @name = @NameNext;
WHILE @@FETCH_STATUS = 0
BEGIN
IF @NameNext != @name
BEGIN
INSERT @RegionTable
SELECT @region
,@name
SELECT @region = @regionNext
,@name = @NameNext
END
ELSE
SET @region = COALESCE(@region + ', ', SPACE(0)) + @regionNext;
FETCH NEXT
FROM RegionCursor
INTO @regionNext
,@NameNext
END
INSERT @RegionTable
SELECT @region
,@name
CLOSE RegionCursor;
DEALLOCATE RegionCursor;
然而,当这是 运行 时,它 return 是没有合并任何内容的原始数据集。我应该如何将查询修改为 return 所需的数据集?
您可以使用 CTE,它可能更干净一些:
;WITH CTE AS
( SELECT Region,
Name,
rn = ROW_NUMBER() OVER (PARTITION BY Name ORDER BY Name)
FROM Table
)
SELECT c1.Region + ',' + c2.Region,
c1.Name
FROM CTE c1
INNER JOIN CTE c2 ON c2.rn = c1.rn + 1
你不需要光标使用 XML PATH
技巧来做到这一点。
SELECT Name,
LEFT(cs.Region, Len(cs.Region) - 1) AS Region
FROM Yourtable a
CROSS APPLY (SELECT Region + ','
FROM Yourtable B
WHERE a.name = b.name
FOR XML PATH('')) cs (Region)
GROUP BY Name,
LEFT(cs.Region, Len(cs.Region) - 1)
我有一个查询 return 是一个如下所示的数据集:
Region Name
-------------------------------------------------------------
Canada Jim
Canada Michael
Canada Andy
Mexico Jim
Mexico Michael
Mexico Kevin
但我想 return 改成这样:
Region Name
-------------------------------------------------------------
Canada, Mexico Jim
Canada, Mexico Michael
Canada Andy
Mexico Kevin
当名称相等时,我的游标查询尝试合并区域名称
OPEN RegionCursor
FETCH NEXT
FROM RegionCursor
INTO @regionNext
,@NameNext
SET @name = @NameNext;
WHILE @@FETCH_STATUS = 0
BEGIN
IF @NameNext != @name
BEGIN
INSERT @RegionTable
SELECT @region
,@name
SELECT @region = @regionNext
,@name = @NameNext
END
ELSE
SET @region = COALESCE(@region + ', ', SPACE(0)) + @regionNext;
FETCH NEXT
FROM RegionCursor
INTO @regionNext
,@NameNext
END
INSERT @RegionTable
SELECT @region
,@name
CLOSE RegionCursor;
DEALLOCATE RegionCursor;
然而,当这是 运行 时,它 return 是没有合并任何内容的原始数据集。我应该如何将查询修改为 return 所需的数据集?
您可以使用 CTE,它可能更干净一些:
;WITH CTE AS
( SELECT Region,
Name,
rn = ROW_NUMBER() OVER (PARTITION BY Name ORDER BY Name)
FROM Table
)
SELECT c1.Region + ',' + c2.Region,
c1.Name
FROM CTE c1
INNER JOIN CTE c2 ON c2.rn = c1.rn + 1
你不需要光标使用 XML PATH
技巧来做到这一点。
SELECT Name,
LEFT(cs.Region, Len(cs.Region) - 1) AS Region
FROM Yourtable a
CROSS APPLY (SELECT Region + ','
FROM Yourtable B
WHERE a.name = b.name
FOR XML PATH('')) cs (Region)
GROUP BY Name,
LEFT(cs.Region, Len(cs.Region) - 1)