Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

t-SQL Use row number, but on duplicate rows, use the same number

I have some data and want to be able to number each row sequentially, but rows with the same type consecutively, number the same number, and when it's a different type continue numbering. There will only be types 5 and 6, ID is actually more complex than abc123. I've tried rank but I seem to get two different row counts - in the example instead of 1 2 2 3 4 it would be 1 1 2 2

original image

enter image description here

dense rank result

enter image description here

MS SQL 2008 R2

like image 412
user2069895 Avatar asked Aug 13 '13 05:08

user2069895


1 Answers

As far as I understand, you want to number your continous groups

declare @Temp table (id1 bigint identity(1, 1), ID nvarchar(128), Date date, Type int)

insert into @Temp
select 'abc123', '20130101', 5 union all
select 'abc124', '20130102', 6 union all
select 'abc125', '20130103', 6 union all
select 'abc126', '20130104', 5 union all
select 'abc127', '20130105', 6 union all
select 'abc128', '20130106', 6 union all
select 'abc129', '20130107', 6 union all
select 'abc130', '20130108', 6 union all
select 'abc131', '20130109', 5

;with cte1 as (
    select
        *,
        row_number() over (order by T.Date) - row_number() over (order by T.Type, T.Date) as grp
    from @Temp as T
), cte2 as (
    select *, min(Date) over (partition by grp) as grp2
    from cte1
)
select
    T.ID, T.Date, T.Type,
    dense_rank() over (order by grp2)
from cte2 as T
order by id1
like image 52
Roman Pekar Avatar answered Sep 28 '22 18:09

Roman Pekar