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