Skip to content

Instantly share code, notes, and snippets.

@chrispickford
Last active June 20, 2016 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrispickford/2e9b466975cf4bd49befe45c22e21227 to your computer and use it in GitHub Desktop.
Save chrispickford/2e9b466975cf4bd49befe45c22e21227 to your computer and use it in GitHub Desktop.
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