Code :
;WITH cte AS ( SELECT a.ID_CLIENT, a.MOIS, ROW_NUMBER() OVER (PARTITION BY a.ID_CLIENT, CASE WHEN c.MOIS IS NULL THEN 0 ELSE 1 END ORDER BY a.ID_CLIENT, a.MOIS) n FROM @Presence a LEFT JOIN @Presence b ON b.ID_CLIENT = a.ID_CLIENT AND b.MOIS = DATEADD(MONTH, 1, a.MOIS) LEFT JOIN @Presence c ON c.ID_CLIENT = a.ID_CLIENT AND c.MOIS = DATEADD(MONTH, -1, a.MOIS) WHERE b.ID_CLIENT IS NULL OR c.ID_CLIENT IS NULL ) SELECT a.ID_CLIENT, MIN(a.MOIS) MOIS_DEBUT, MAX(a.MOIS) MOIS_FIN, DATEDIFF(MONTH, MIN(a.MOIS), MAX(a.MOIS)) + 1 DUREE FROM cte a GROUP BY a.ID_CLIENT, a.n ORDER BY a.ID_CLIENT, MIN(a.MOIS)
|