sql server - Row_Number() partitioning according to consecutive rows -
i working on query sql server 2008 needs partition in way considers consecutive nature of rows in table, meaning has no "memory" , restart row numbering when consecutiveness breaks down partition.
to illustrate:
declare @test table ( customerid varchar(10), itemid varchar(10), platformname varchar(10), date datetime ) insert @test values ('aaaa', 'x', 'mobile','2015-10-24 22:52:47') insert @test values ('aaaa', 'x', 'mobile','2015-10-23 22:56:47') insert @test values ('aaaa', 'k', 'mobile','2015-10-22 21:52:47') insert @test values ('aaaa', 'k', 'tablet','2015-10-20 22:12:47') insert @test values ('aaaa', 'x', 'mobile','2015-10-19 20:52:47') insert @test values ('aaaa', 'k', 'tablet','2015-10-18 12:52:47') insert @test values ('aaaa', 'k', 'tablet','2015-10-16 12:52:47') select t.*, row_number() on (partition t.customerid,t.itemid,t.platformname order t.date desc) rowno @test t order t.date desc
the following query returns:rowno
1 2 1 1 3 2 3
instead of desired:
1 2 1 1 1 1 2
in case of row 5 , 6 should restart counting because new partition when consider consecutiveness breaks apart initial partition.
i need rank rows in accordance row numbering, follows:
1 1 2 3 4 5 6 7 7
what want create indicator changes when partition changes. can following trick. since row number increments within given partition, if subtract incrementing number within every row same number whole partition sequence.
here chart @ start of partition.
row number partition row number row number-partition number x 1 x-1 x+1 2 x-1 ... x+n n+1 x-1
x change @ next partition partition number start @ 1 , same number every row in partition until next sequential partition.
you use result part of partition , problem solved.
here how code in sql:
with cte as(select *, row_number() over(order date desc) - row_number() over(partition customerid, itemid, platformname order date desc) rn @test) select *, row_number() over(partition customerid, itemid, platformname, rn order date desc) rn2 cte order date desc
Comments
Post a Comment