Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Cambia la colonna del numero

Questo è un problema di lacune e isole.

Un approccio. SQL Fiddle

WITH T1
     AS (SELECT *,
                ROW_NUMBER()
                  OVER (
                    PARTITION BY NAME
                    ORDER BY DATE) - ROW_NUMBER()
                                       OVER (
                                         PARTITION BY NAME, [PAY]
                                         ORDER BY DATE) AS Grp
         FROM   Table1),
     T2
     AS (SELECT *,
                MIN(DATE)
                  OVER (
                    PARTITION BY NAME, Grp) AS MinDate
         FROM   T1)
SELECT [NAME],
       [PAY],
       [DATE],
       DENSE_RANK()
         OVER (
           PARTITION BY NAME
           ORDER BY MinDate) AS CHANGEGROUP
FROM   T2
ORDER  BY NAME,
          MinDate