Created
April 23, 2014 21:45
-
-
Save matheusoliveira/11233548 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
SELECT (SELECT | |
string_agg( | |
CASE | |
WHEN lag IS NULL THEN to_char(code, 'FM000') | |
WHEN lag <> code - 1 THEN to_char(code, '","FM000') | |
WHEN lead IS NULL OR lead <> code + 1 THEN to_char(code, '"-"FM000') | |
END | |
, '') | |
FROM (SELECT code, lead(code) OVER(ORDER BY code), lag(code) OVER(ORDER BY code) FROM unnest((string_to_array(replace(code, ' ', ''), ','))::INT[]) AS code ORDER BY code) t1 WHERE lead IS NULL OR lag IS NULL OR lead <> code + 1 OR lag <> code - 1) | |
FROM ( | |
VALUES | |
('001, 002'), | |
('340'), | |
('001, 002, 003'), | |
('444, 445'), | |
('406, 407'), | |
('415, 416, 417'), | |
('415, 416, 417, 420, 421'), | |
('412, 413, 414') | |
) t(code); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment