DENSE_RANK according to particular order

前端 未结 2 440
天涯浪人
天涯浪人 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

    0 讨论(0)
  • 2021-01-18 06:43

    First rank distinct names ordered by date and then join on the table:

    ;WITH cte AS(SELECT name, ROW_NUMBER() OVER(ORDER BY MIN(date)) rn 
                 FROM dbo.MyTable 
                 GROUP BY name)
    SELECT c.rn, m.date, m.name
    FROM cte c
    JOIN dbo.MyTable m ON m.name = c.name
    ORDER BY m.date
    
    0 讨论(0)
提交回复
热议问题