sql >> Base de Datos >  >> RDS >> Sqlserver

Implementación de cte requerida para datos jerárquicos

Puedes hacer un ROW_NUMBER() con PARTITION BY y luego haga una autounión con rn =rn + 1 y haga un DATEDIFF según el cual puede agrupar sus resultados.

Prueba algo como esto

DECLARE @Rules TABLE(RuleId  INT,Name CHAR(3),    StartDate DATE,           EndDate DATE)

INSERT INTO @Rules VALUES
(3 ,'TP3', '3/18/2015', '11/28/2015'),
(3 ,'TP3', '11/28/2015', '4/30/2016'),
(3 ,'TP3', '4/30/2016', '10/5/2016'),
(3 ,'TP3', '10/25/2016', '11/15/2016'),
(3 ,'TP3', '11/15/2016', null) 


;WITH CTE AS 
(
SELECT ROW_NUMBER() OVER(PARTITION BY RuleID ORDER BY StartDate) rn,*
FROM @Rules
), CTE2 AS
(
SELECT ISNULL(DATEDIFF(day,C1.EndDate,C2.StartDate),0) diff,C1.*
FROM CTE C1 
LEFT JOIN CTE C2 ON C1.rn + 1 = C2.rn
 AND C1.RuleId = C2.RuleId
)
SELECT RuleId,Name,MIN(StartDate)  StartDate,NULLIF(MAX(CASE WHEN EndDate IS NULL THEN '2999/12/31' ELSE EndDate END),'2999/12/31') EndDate
FROM
(
SELECT C2.Diff,C1.RuleId,C1.Name,C1.StartDate,C1.EndDate
FROM CTE2 C1
CROSS APPLY (SELECT ISNULL(SUM(Diff),0) Diff FROM CTE2 C2 WHERE C1.StartDate > C2.StartDate AND C1.RuleId = C2.RuleId) C2
) C
GROUP BY RuleId,Name,Diff
ORDER BY RuleId,Diff