Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 340
roman m Avatar asked Sep 23 '08 18:09

roman m


People also ask

How can I get multiple values from a single column in SQL?

Using an OR condition enables you to specify several alternative values to search for in a column. This option expands the scope of the search and can return more rows than searching for a single value. You can often use the IN operator instead to search for multiple values in the same data column.

How can I return multiple values in SQL?

A SQL Server function can return a single value or multiple values. To return multiple values, the return type of the the function should be a table. Running the query will list out 10 consecutive dates starting from today, as shown below: As you can see, the return type of the function test_function is a table.

How do I return multiple columns in SQL?

Using the SELECT Statement to Retrieve Data in SQL To retrieve multiple columns from a table, you use the same SELECT statement. The only difference is that you must specify multiple column names after the SELECT keyword, and separate each column by a comma.


2 Answers

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 
like image 174
Scott Nichols Avatar answered Sep 24 '22 00:09

Scott Nichols


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     */ 
like image 42
leoinfo Avatar answered Sep 20 '22 00:09

leoinfo