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 TABLE MyTable
SELECT * INTO MyTable FROM (
VALUES ('2015-12-23', 'ccc'),('2015-12-21', 'aaa'),
('2015-12-20', 'bbb'),('2015-12-22', 'aaa')
) t (date, name)
SELECT DENSE_RANK() OVER (ORDER BY name) rank, * FROM MyTable ORDER BY date
For the query above I got
rank date name
2 2015-12-20 bbb
1 2015-12-21 aaa
1 2015-12-22 aaa
3 2015-12-23 ccc
You can see the dates are sorted (good), ranks are assigned to names in group (good), but the ranks do not start from the first group of name, e.g. I want
rank date name
1 2015-12-20 bbb
2 2015-12-21 aaa
2 2015-12-22 aaa
3 2015-12-23 ccc
How would you correct the query? If there are multiple working answers, the simplest/shortest one will be picked as the answer. Thanks.
Added:
Thanks @lad2025 and @GiorgosBetsos for clarifying my question. Sorting is straightly according to dates and dates are unique in my case. Names can repeat and appear non-consecutively. So with ('2015-12-24', 'aaa')
, the output is
rank date name
1 2015-12-20 bbb
2 2015-12-21 aaa
2 2015-12-22 aaa
3 2015-12-23 ccc
4 2015-12-24 aaa