Sqlserver
 sql >> Base de Dados >  >> RDS >> Sqlserver

Agrupar linhas por condição


Você pode usar Recursive CTE . Não consigo pensar em nenhuma maneira melhor.
;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)