How to return multiple values in one column (T-SQL

2019-01-01 15:35发布

I have a table UserAliases (UserId, Alias) with multiple aliases per user. I need to query it and return all aliases for a given user, the trick is to return them all in one column.

Example:

UserId/Alias  
1/MrX  
1/MrY  
1/MrA  
2/Abc  
2/Xyz

I want the query result in the following format:

UserId/Alias  
1/ MrX, MrY, MrA  
2/ Abc, Xyz

Thank you.

I'm using SQL Server 2005.

p.s. actual T-SQL query would be appreciated :)

9条回答
十年一品温如言
2楼-- · 2019-01-01 15:55

You can use a function with 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
查看更多
裙下三千臣
3楼-- · 2019-01-01 16:05
DECLARE @Str varchar(500)

SELECT @Str=COALESCE(@Str,'') + CAST(ID as varchar(10)) + ','
FROM dbo.fcUser

SELECT @Str
查看更多
伤终究还是伤i
4楼-- · 2019-01-01 16:09

Have a look at this thread already on StackOverflow, it conveniently gives you a T-SQL example.

查看更多
登录 后发表回答