Это синтаксис SQL Server, та же методология, что и в Barbaros. В попытке быть настолько пуристом, насколько это возможно, я попытался выполнить самостоятельное объединение вместо использования LAG
, но это по общему признанию затрудняет чтение запроса.
SELECT clientid, MIN(startdate) AS startdate, MAX(enddate) AS enddate
FROM (SELECT *, SUM(CASE WHEN a.enddate_prev = a.startdate THEN 0 ELSE 1 END) OVER (ORDER BY clientid, startdate) sm
FROM (SELECT clientid, startdate, enddate,
LAG(enddate, 1, NULL) OVER (PARTITION BY clientid ORDER BY clientid, enddate) enddate_prev
FROM client_dates) a) b
GROUP BY clientid, sm
Установите таблицу так:
CREATE TABLE client_dates (clientid INT NOT NULL, startdate DATE NOT NULL, enddate DATE NOT NULL);
INSERT INTO client_dates VALUES (1, TRY_PARSE('10.10.2017' AS datetime USING 'en-GB'), TRY_PARSE('12.10.2017' AS datetime USING 'en-GB'));
INSERT INTO client_dates VALUES (1, TRY_PARSE('12.10.2017' AS datetime USING 'en-GB'), TRY_PARSE('13.10.2017' AS datetime USING 'en-GB'));
INSERT INTO client_dates VALUES (1, TRY_PARSE('13.10.2017' AS datetime USING 'en-GB'), TRY_PARSE('17.10.2017' AS datetime USING 'en-GB'));
INSERT INTO client_dates VALUES (1, TRY_PARSE('10.11.2017' AS datetime USING 'en-GB'), TRY_PARSE('17.11.2017' AS datetime USING 'en-GB'));
INSERT INTO client_dates VALUES (1, TRY_PARSE('17.11.2017' AS datetime USING 'en-GB'), TRY_PARSE('23.11.2017' AS datetime USING 'en-GB'));
INSERT INTO client_dates VALUES (1, TRY_PARSE('12.12.2017' AS datetime USING 'en-GB'), TRY_PARSE('14.12.2017' AS datetime USING 'en-GB'));
INSERT INTO client_dates VALUES (2, TRY_PARSE('10.11.2017' AS datetime USING 'en-GB'), TRY_PARSE('15.11.2017' AS datetime USING 'en-GB'));
INSERT INTO client_dates VALUES (2, TRY_PARSE('01.12.2017' AS datetime USING 'en-GB'), TRY_PARSE('02.12.2017' AS datetime USING 'en-GB'));
INSERT INTO client_dates VALUES (2, TRY_PARSE('02.12.2017' AS datetime USING 'en-GB'), TRY_PARSE('05.12.2017' AS datetime USING 'en-GB'));