Discussion Locked

Multi records in single row

0 helpful
4 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

I Have a small table named "MGR" with two fields named "Manager","Heads" with 5 records.

My Table data could be

MANAGER HEADS
Chris A
Harris B
Chris C
Harris D
Chris E

I need a single query which would display the result in two rows as follows

MANAGER HEADS
Chris A,C,E
Harris B,D

Could someone solve my pblm

4 replies

by john_wills

"LeftFile": SELECT DISTINCT Manager from MGR;

"AFile": SELECT Manager Heads from MGR WHERE Heads="A";
sim BFile, CFile

SELECT LeftFile.Manager,AFile.Heads AS HeadsA,BFile.Heads AS HeadsB,CFile.Heads AS HeadsC from LeftFile LEFT JOIN AFile ON LeftFile.Manager=AFile.Manager with 2 similar LEFT JOIN more

by ajsunil

Thanks for the interest shown,i'm using .net with sql server ,
my table can have n number of records,so do u mean that i should use n number of joins and alias name.

by allersj

Here is something you can try, although it requires the use of a user defined function in order to accomplish the desired results.

1) Create a function that will return all the heads for a single manager. With the input parameter 'Chris', the function returns 'A,C,E'.

Here is a rough example:

CREATE FUNCTION dbo.GetHeadsList
(@Person VARCHAR(50))
RETURNS varchar(255)
AS
BEGIN

DECLARE @HeadsList AS varchar(255)
SET @HeadsList = ''

SELECT @HeadsList = @HeadsList + [ManagerHeads].Heads + ','
FROM
(SELECT MGR.HEADS
FROM MGR
WHERE (Manager = @Person )) [ManagerHeads]

IF LEN(@HeadsList) = 0
-- Set to NULL if there is no row exist in MGR for Person (Person is not a manager?)
SET @HeadsList = NULL
ELSE
-- Remove trailing comma
SET @HeadsList = LEFT(@HeadsList, LEN(@HeadsList) - 1)

RETURN @HeadsList
END

2) The query to get the desired results would look something like:

SELECT DISTINCT MGR.Manager [MANAGER], dbo.GetHeadsList(MGR.Manager) [HEADS]
FROM MGR

I'm not sure if this meets your requirements or if this is even an efficient or practical solution, but maybe it will lead to something usable.

John

This discussion is closed to new replies.