在SQL Server中合并具有相同ID的多行

时间:2019-06-10 21:45:36

标签: sql-server merge

在SQL Server中将具有相同ID的多行值组合在一起的最有效方法是什么?

原始数据表q)fills[1;] -1+x+1 1 2 3 3 3 20 30 30 30 2 3 3 3 20 30 30 30 2 3 3 3 20 30 30 30 2 3 3 3 20 30 3..

dbo.ProductCategory

我正在尝试获得以下结果

+-----------+----------+------+
| ProductID |  CATID   |  AA  |
+-----------+----------+------+
|  1        | 123      | A    |
|  1        | 412      | B    |
|  2        | 567      | C    |
|  2        | 521      | A    |
|  3        |   2      | D    |
|  3        |   5      | A    |
|  4        |   6      | C    |
|  4        |   8      | E    |
|  4        | 123      | A    |
+----+------+----------+------+

2 个答案:

答案 0 :(得分:0)

在SQL Server 2017+中,您可以使用STRING_AGG

select ProductId, STRING_AGG(CATID, ',') as CATID, STRING_AGG(AA, ',') AA
from PC
GROUP BY ProductID

答案 1 :(得分:0)

样本数据

DECLARE @Temp AS TABLE (ProductID INT,  CATID  INT,  AA  CHAR(2))
INSERT INTO @Temp
SELECT 1 , 123 , 'A' UNION ALL    
SELECT 1 , 412 , 'B' UNION ALL    
SELECT 2 , 567 , 'C' UNION ALL    
SELECT 2 , 521 , 'A' UNION ALL    
SELECT 3 ,   2 , 'D' UNION ALL    
SELECT 3 ,   5 , 'A' UNION ALL    
SELECT 4 ,   6 , 'C' UNION ALL    
SELECT 4 ,   8 , 'E' UNION ALL    
SELECT 4 , 123 , 'A' 

在SQL Server中使用STUFF()

SELECT ProductID,STUFF((SELECT CONCAT(', ', CATID) 
                        FROM @Temp i 
                        WHERE i.ProductID = o.ProductID
                FOR XML PATH ('')),1,1,'') AS CATID
                ,STUFF((SELECT CONCAT(', ', AA) 
                        FROM @Temp i 
                        WHERE i.ProductID = o.ProductID
                FOR XML PATH ('')),1,1,'') AS AA
FROM @Temp o
GROUP BY ProductID

结果

ProductID   CATID         AA
------------------------------------
1           123, 412     A , B 
2           567, 521     C , A 
3           2, 5         D , A 
4           6, 8, 123    C , E , A