I have a set of 'followed' rows with the same value and I want to group them together to make a from and to. The proposed solution is usually to use ROW_NUMBER()
and then group, but I find that there are cases that do not work, with an example it will be better understood:
WITH
CTE AS
(SELECT *
FROM (VALUES ('A', 37, ''),
('A', 38, ''),
('A', 39, ''),
('A', 40, ''),
('A', 41, ''),
('A', 42, ''),
('A', 43, ''),
('B', 44, '=> error Grupo 43'),
('B', 45, '=> error Grupo 43'),
('C', 46, ''),
('C', 47, ''),
('B', 48, ''),
('B', 49, ''),
('B', 50, ''),
('A', 51, '=> error Grupo 43'),
('A', 52, '=> error Grupo 43'),
('A', 53, '=> error Grupo 43')) DATA (LETRA, DESDE, ERROR) )
SELECT *,
ROW_NUMBER() OVER (PARTITION BY LETRA ORDER BY DESDE) AS rn,
DESDE - ROW_NUMBER() OVER (PARTITION BY LETRA ORDER BY DESDE) AS Grupo
FROM CTE
ORDER BY SINCE;
Is there a way to 'group' the records correctly?
a greeting