June 16, 2011 at 1:37 am
Hi,
I have a set of rows that need to be pivoted. Pls find the table strucutre below.
RowID Int Auto Identity
Col1 Int Primary Key
Col2 Int Primary Key
Col3 Int Primary Key
ErrorCD varchar(10)
In the above table each composite Pkey will be having more than one error code. When we query this table this looks like as below...
RowID Col1 Col2 Col3 ErroCD
1 A1 B1 C1 E1
2 A1 B1 C1 E2
3 A1 B1 C1 E3
4 A2 B1 C1 E1
5 A2 B1 C1 E2
6 A2 B1 C1 E3
7 A3 B1 C1 E1
8 A3 B1 C1 E2
9 A3 B1 C1 E3
This should be displayed in the below format...
Col1 Col2 Col3 ErrorCD
A1 B1 C1 E1,E2,E3
A2 B1 C1 E1,E2,E3
A3 B1 C1 E1,E2,E3
Pls help..
Thanks in advance!
June 16, 2011 at 2:31 am
DECLARE @T TABLE(RowID INT, Col1 CHAR(2), Col2 CHAR(2), Col3 CHAR(2), ErrorCD VARCHAR(10))
INSERT INTO @T(RowID,Col1,Col2,Col3,ErrorCD)
SELECT 1, 'A1', 'B1', 'C1', 'E1' UNION ALL
SELECT 2, 'A1', 'B1', 'C1', 'E2' UNION ALL
SELECT 3, 'A1', 'B1', 'C1', 'E3' UNION ALL
SELECT 4, 'A2', 'B1', 'C1', 'E1' UNION ALL
SELECT 5, 'A2', 'B1', 'C1', 'E2' UNION ALL
SELECT 6, 'A2', 'B1', 'C1', 'E3' UNION ALL
SELECT 7, 'A3', 'B1', 'C1', 'E1' UNION ALL
SELECT 8, 'A3', 'B1', 'C1', 'E2' UNION ALL
SELECT 9, 'A3', 'B1', 'C1', 'E3';
SELECT T1.Col1,T1.Col2,T1.Col3,
STUFF((SELECT ','+T2.ErrorCD AS "text()"
FROM @T T2
WHERE T2.Col1=T1.Col1
AND T2.Col2=T1.Col2
AND T2.Col3=T1.Col3
ORDER BY T2.ErrorCD
FOR XML PATH('')
),1,1,'') AS ErrorCD
FROM @T T1
GROUP BY T1.Col1,T1.Col2,T1.Col3;
____________________________________________________
Deja View - The strange feeling that somewhere, sometime you've optimised this query before
How to get the best help on a forum
http://www.sqlservercentral.com/articles/Best+Practices/61537June 16, 2011 at 4:51 am
Thank you. That helps!! 🙂
Viewing 3 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply