Friday, March 30, 2012

Query Help

Hello,

I am not sure whether is possible to do that with query.

I have this table

User Flag
A X1
A X2
A X3
B X1
B X5
C X7

and I need to get this table

User All_Flags
A X1 X2 X3
B X1 X5
C X7

Thank you for help
DJThis has been very popular lately

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=40520|||I'd use:CREATE TABLE Drahos (
[User] CHAR(1)
, Flag CHAR(2)
)

INSERT INTO Drahos (
[user], Flag
) SELECT 'A', 'X1' UNION ALL SELECT 'A', 'X2'
UNION ALL SELECT 'A', 'X3' UNION ALL SELECT 'B', 'X1'
UNION ALL SELECT 'B', 'X5' UNION ALL SELECT 'C', 'X7'
GO
CREATE FUNCTION dbo.fDrahos(
@.pcUser CHAR(1)
) RETURNS VARCHAR(255) AS BEGIN

DECLARE @.cFlags VARCHAR(255)

SELECT @.cFlags = Coalesce(@.cFlags + ',', '') + Flag
FROM Drahos
WHERE [User] = @.pcUser

RETURN @.cFlags
END
GO

SELECT DISTINCT [User], dbo.fDrahos([User]) AS All_Flags
FROM Drahos-PatP|||Maybe it's a new question on a certification test ;-)

No comments:

Post a Comment