gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:38:26 24 4
gpt4 key购买 nike

我有一些数据,希望能够按顺序对每一行进行编号,但是具有相同类型的行连续编号,对相同的数字进行编号,当它是不同类型时继续编号。只会有类型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

最佳答案

据我了解,您想要对连续组进行编号

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

关于sql - t-SQL 使用行号,但在重复的行上使用相同的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18201606/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com