Skip to content

Instantly share code, notes, and snippets.

@matheusoliveira
Created April 23, 2014 21:45
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 matheusoliveira/11233548 to your computer and use it in GitHub Desktop.
Save matheusoliveira/11233548 to your computer and use it in GitHub Desktop.
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