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

Agrupar filas por condición

Puedes usar Recursive CTE . No puedo pensar en una mejor manera.

;WITH cte
     AS (SELECT *,
                Row_number()OVER(ORDER BY start) rn
         FROM   Yourtable),
     rec_cte
     AS (SELECT *,
                ( [End] - Start ) AS st,
                1                 AS grp
         FROM   cte
         WHERE  rn = 1
         UNION ALL
         SELECT a.*,
                CASE
                  WHEN st + ( a.[End] - a.Start ) >= 500 THEN a.[End] - a.Start
                  ELSE st + ( a.[End] - a.Start )
                END,
                CASE
                  WHEN st + ( a.[End] - a.Start ) >= 500 THEN b.grp + 1
                  ELSE grp
                END
         FROM   cte a
                JOIN rec_cte b
                  ON a.rn = b.rn + 1)
SELECT Min(Start) as Start,
       Max([End]) as [End],
       Max(st) as Quantity
FROM   rec_cte
GROUP  BY grp
OPTION (maxrecursion 0)