DENSE_RANK according to particular order

前端 未结 2 459
天涯浪人
天涯浪人 2021-01-18 05:59

Hi I have a table of data I want to output the dense_rank of the names starting from the first group of names according to sorted dates order. e.g.

DROP TABL         


        
2条回答
  •  [愿得一人]
    2021-01-18 06:36

    You can use:

    SELECT DENSE_RANK() OVER (ORDER BY minGrpDate),
           [date], name
    FROM (
      SELECT MIN([date]) OVER (PARTITION BY grp) AS minGrpDate,
             [date], name
      FROM (       
        SELECT [date], name,
               ROW_NUMBER() OVER (ORDER BY [date])
               -
               ROW_NUMBER() OVER (PARTITION BY name ORDER BY [date]) AS grp
        FROM mytable) AS t ) AS s
    ORDER BY Date
    

    Explanation:

    • grp field identifies islands of consecutive records having the same name.
    • minGrpDate, which is calculated using grp, is the minimum date of each island.
    • Using minGrpDate we can now apply DENSE_RANK() to get required rank.

    Note1: The above query handles discontinuities in name field, i.e. the case of non-consecutive fields having the same name.

    Note2: The query does not handle the case of different name values sharing the same date value.

    Demo here

提交回复
热议问题