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:45

Well... I see that an answer was already accepted... but I think you should see another solutions anyway:

/* 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    
*/
查看更多
无与为乐者.
3楼-- · 2019-01-01 15:45

My boss wrote up an article on this way back 2003: Concatenation with COALESCE

查看更多
骚的不知所云
4楼-- · 2019-01-01 15:46

Sorry, read the question wrong the first time. You can do something like this:

declare @result varchar(max)

--must "initialize" result for this to work
select @result = ''

select @result = @result + alias
FROM aliases
WHERE username='Bob'
查看更多
孤独总比滥情好
5楼-- · 2019-01-01 15:48

You can either loop through the rows with a cursor and append to a field in a temp table, or you could use the COALESCE function to concatenate the fields.

查看更多
浪荡孟婆
6楼-- · 2019-01-01 15:48

group_concat() sounds like what you're looking for.

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

since you're on mssql, i just googled "group_concat mssql" and found a bunch of hits to recreate group_concat functionality. here's one of the hits i found:

http://www.stevenmapes.com/index.php?/archives/23-Recreating-MySQL-GROUP_CONCAT-In-MSSQL-Cross-Tab-Query.html

查看更多
旧人旧事旧时光
7楼-- · 2019-01-01 15:54

this is one of the fastest and simplest ways to do what you need without the need for a UDF: http://weblogs.sqlteam.com/mladenp/archive/2007/06/01/60220.aspx

there's one other way using a numbers table that is faster for really large datasets but i don't think you'll need that.

查看更多
登录 后发表回答