如何在一列中返回多个值(T-SQL)? [英] How to return multiple values in one column (T-SQL)?
本文介绍了如何在一列中返回多个值(T-SQL)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个表 UserAliases
(UserId, Alias
),每个用户有多个别名.我需要查询它并返回给定用户的所有别名,诀窍是将它们全部返回到一列中.
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.
示例:
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
谢谢.
我使用的是 SQL Server 2005.
I'm using SQL Server 2005.
附言实际的 T-SQL 查询将不胜感激:)
p.s. actual T-SQL query would be appreciated :)
推荐答案
您可以通过 COALESCE 使用函数.
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
这篇关于如何在一列中返回多个值(T-SQL)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文