Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have NAME and PAY, but I need CHANGEGROUP in this example:

NAME   PAY  DATE    CHANGEGROUP
Sally   12  10/01/2011  1
Sally   12  10/01/2011  1
Sally   12  11/02/2011  1
Sally   12  11/02/2011  1
Sally   12  12/01/2012  1
Sally   13  04/23/2013  2
Sally   12  04/24/2013  3
Sally   10  05/01/2013  4
Sally   10  10/01/2014  4

I tried RANK() and DENSE_RANK(), but they group according to the value - because pay goes down, it messes up my grouping. I saw this but it's not compatible with this older version of SQL 2005

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
301 views
Welcome To Ask or Share your Answers For Others

1 Answer

This is a gaps and islands problem.

One approach. 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 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...