5

我有一些数据,希望能够按顺序对每一行进行编号,但是连续编号相同类型的行,编号相同的编号,并且当它是不同类型时继续编号。只会有类型 5 和 6,ID 实际上比 abc123 更复杂。我试过排名,但我似乎得到了两个不同的行数 - 在示例中而不是 1 2 2 3 4 它将是 1 1 2 2

原始图像

在此处输入图像描述

密集秩结果

在此处输入图像描述

微软 SQL 2008 R2

4

1 回答 1

6

据我了解,你想给你的连续组编号

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
于 2013-08-13T05:54:58.387 回答