A DENSE_RANK() Sample (T-SQL)


if object_id('test','U') is not null
Drop table test

Create table test (t int, ID int)
Insert into test values (6,1),
(6,	2),
(6,	3),
(6,	4),
(6,	5),
(11,	6),
(11,	7),
(5,	8),
(5,	9),
(10,	10),
(10,	11),
(4,	12),
(4,	13),
(9,	14),
(3,	15),
(3,	16),
(8,	17),
(2,	18),
(2,	19),
(7,	20)

;with mycte as
(select *,  row_number() over(order by ID) - row_number() over(partition by t order by ID) rnDelta from test
)
Select dense_rank()Over(  order by rndelta ) X, T, id from mycte
order by id
/*
X	T	id
1	6	1
1	6	2
1	6	3
1	6	4
1	6	5
2	11	6
2	11	7
3	5	8
3	5	9
4	10	10
4	10	11
5	4	12
5	4	13
6	9	14
7	3	15
7	3	16
8	8	17
9	2	18
9	2	19
10	7	20

*/
--http://social.msdn.microsoft.com/Forums/en-US/transactsql/thread/b14e4533-14c8-45fc-b50a-565a36bbb9da

Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s