t-SQL使用行号,但在重复行上,使用相同的数字

时间:2013-08-13 05:52:23

标签: sql sql-server tsql

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

原始图片

enter image description here

密集排名结果

enter image description here

MS SQL 2008 R2

1 个答案:

答案 0 :(得分: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