我有一个table UserAliases
(UserId, Alias
)每个用户有多个别名.我需要查询它并返回给定用户的所有别名,诀窍是将它们全部返回到一列中.
例:
UserId/Alias 1/MrX 1/MrY 1/MrA 2/Abc 2/Xyz
我希望查询结果采用以下格式:
UserId/Alias 1/ MrX, MrY, MrA 2/ Abc, Xyz
谢谢.
我正在使用SQL Server 2005.
ps实际的T-SQL查询将不胜感激:)
您可以使用COALESCE的功能.
CREATE FUNCTION [dbo].[GetAliasesById] ( @userID int ) RETURNS varchar(max) AS BEGIN declare @output varchar(max) select @output = COALESCE(@output + ', ', '') + alias from UserAliases where userid = @userID return @output END GO SELECT UserID, dbo.GetAliasesByID(UserID) FROM UserAliases GROUP BY UserID GO
嗯......我看到答案已被接受......但我认为你应该看到另一种解决方案:
/* EXAMPLE */ DECLARE @UserAliases TABLE(UserId INT , Alias VARCHAR(10)) INSERT INTO @UserAliases (UserId,Alias) SELECT 1,'MrX' UNION ALL SELECT 1,'MrY' UNION ALL SELECT 1,'MrA' UNION ALL SELECT 2,'Abc' UNION ALL SELECT 2,'Xyz' /* QUERY */ ;WITH tmp AS ( SELECT DISTINCT UserId FROM @UserAliases ) SELECT LEFT(tmp.UserId, 10) + '/ ' + STUFF( ( SELECT ', '+Alias FROM @UserAliases WHERE UserId = tmp.UserId FOR XML PATH('') ) , 1, 2, '' ) AS [UserId/Alias] FROM tmp /* -- OUTPUT UserId/Alias 1/ MrX, MrY, MrA 2/ Abc, Xyz */