Thank you very much for your answer. Here are realistic data from my database, to check the code: CREATE table pos ( pos NVARCHAR(1), start DATETIME, CONSTRAINT "pk_pos" PRIMARY KEY (pos, start) ); INSERT INTO POS (pos, start) VALUES ('0', '2019-01-01 00:00:00'), ('1', '2019-06-02 11:00:00'), ('2-3', '2019-06-03 11:30:00'), ('4-5', '2019-06-04 00:30:00'), ('6', '2019-06-04 03:00:00'), ('7-9', '2019-06-04 20:20:00'), ('10', '2019-06-05 21:43:00'), ('11-12', '2019-06-26 09:13:00'), ('13', '2019-06-28 06:00:00'), ('14-16', '2019-06-28 11:00:00'), ('17-18', '2019-07-01 17:00:00'), ('19-20', '2019-07-02 02:45:00'), ('0', '2019-07-03 02:15:00');