可能重复:
SQL Server: Can I Comma Delimit Multiple Rows Into One Column?
我有表X(X_ID,X_Name)是1-M与表Y(Y_ID,Y_Value)
表X:
X_ID X_Name
---- ------
12 foo
14 foo2
16 foo3
表Y:
X_ID Y_Value
---- -------
12 A
12 B
14 C
14 D
14 E
16 F
16 G
如何使用T-Sql获得以下结果?
X_ID X_Name Y_Value
---- ------ ------
12 foo A,B
14 foo2 C,D,E
16 foo3 F,G
由于
答案 0 :(得分:15)
SELECT X.X_ID, X.X_Name, Y_Values = STUFF((SELECT ',' + Y_Value FROM dbo.Y
WHERE Y.X_ID = X.X_ID
FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'), 1, 1, '')
FROM dbo.X;
在SQL Server 2017和Azure SQL数据库中,您可以使用新的STRING_AGG()
函数:
SELECT x.X_ID, x.X_Name,
Y_Values = STRING_AGG(Y.Y_Value,',')
FROM dbo.X
INNER JOIN dbo.Y
ON X.X_ID = Y.X_ID
GROUP BY x.X_ID, x.X_Name;
如果您不喜欢默认订单,可以使用WITHIN GROUP
指定它:
SELECT x.X_ID, x.X_Name,
Y_Values = STRING_AGG(Y.Y_Value,',') WITHIN GROUP (ORDER BY Y.Y_Value)
FROM dbo.X
INNER JOIN dbo.Y
ON X.X_ID = Y.X_ID
GROUP BY x.X_ID, x.X_Name;