November 5, 2008 at 11:53 am
I've got a table that I'm trying to query with a self join that I must not be doing correctly. Any help would be greatly appreciated. The table looks something like below:
A B C
1 x 1
1 y 1
2 z 1
3 a 2
3 b null
3 c 2
4 d null
what I'm trying to pull out is for all unique column A values, a second column with the values in B concatenated if C is not null, so the result set for the above data would be:
1 xy
2 z
3 ac
hopefully that makes sense, and thanks in advance for your help!
November 5, 2008 at 1:48 pm
You should provide sample code for next time
but after some scratching my head, I have to resolve to XML method (can be used in SQL2005 so should work for you)
Customize to your situation
-- Jerry Hung
SET XACT_ABORT, NOCOUNT ON
DECLARE @test TABLE (
A VARCHAR(10),
B VARCHAR(10),
C VARCHAR(10)
)
INSERT INTO @test
SELECT'1','x','1'
UNION ALL
SELECT'1','y','1'
UNION ALL
SELECT'2','z','1'
UNION ALL
SELECT'3','a','2'
UNION ALL
SELECT'3','b',NULL
UNION ALL
SELECT'3','c','2'
UNION ALL
SELECT'4','d',NULL
--SELECT * FROM @test
/*
A B C
1 x 1
1 y 1
2 z 1
3 a 2
3 b null
3 c 2
4 d null
*/
SELECT
T1.A
,Test=
REPLACE((
SELECT B [data()] FROM @test T3
WHERE T3.A=T1.A
AND T3.C IS NOT NULL
FOR XML PATH('')
), ' ', '')
FROM @test T1
WHERE T1.C IS NOT NULL
GROUP BY T1.A
/*
1 xy
2 z
3 ac
*/
November 5, 2008 at 8:07 pm
... and please see the following article for some potential problems you can avoid with some other methods of concatenation...
http://www.sqlservercentral.com/articles/Test+Data/61572/
Jerry's method does not have such problems.
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 3 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply