Sqlserver
 sql >> Base de données >  >> RDS >> Sqlserver

Regrouper les lignes par condition

Vous pouvez utiliser Recursive CTE . Je ne peux pas penser à une meilleure façon.

;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)