Last active
June 20, 2016 15:02
-
-
Save chrispickford/2e9b466975cf4bd49befe45c22e21227 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DECLARE @table TABLE ( | |
ID INT IDENTITY(1, 1) | |
PRIMARY KEY, | |
A1 CHAR(2), | |
A2 CHAR(2), | |
A3 CHAR(2), | |
A4 CHAR(2) | |
); | |
INSERT INTO @table | |
(A1, A2, A3, A4) | |
VALUES ('P1', 'P4', 'P2', 'P3'), | |
('P2', 'P3', 'P1', 'P3'); | |
SELECT t.ID, | |
t.A1, | |
t.A2, | |
t.A3, | |
t.A4, | |
STUFF(( | |
SELECT ' | ' + unpvt.Val | |
FROM @table UNPIVOT ( Val FOR Col IN (A1, A2, A3, A4) ) unpvt | |
WHERE unpvt.ID = t.ID | |
ORDER BY unpvt.Val | |
FOR | |
XML PATH('') | |
), 1, 3, '') AS ORDERED_DATA | |
FROM @table AS t; | |
/* | |
ID A1 A2 A3 A4 ORDERED_DATA | |
1 P1 P4 P2 P3 P1 | P2 | P3 | P4 | |
2 P2 P3 P1 P3 P1 | P2 | P3 | P3 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment