Sql server SQL查询,每次找到唯一编号时开始对行ID进行编号
例如,有没有任何可能的方法可以为类似类型的号码获取唯一idSql server SQL查询,每次找到唯一编号时开始对行ID进行编号,sql-server,Sql Server,例如,有没有任何可能的方法可以为类似类型的号码获取唯一id H_ID ROW_ID 1 1 1 2 1 3 2 1 2 2 3 1 3 2 如图所示,1重复3次,因此数字为1,2,3,然后再次以1开头 declare @table table (h_id int) insert into @table selec
H_ID ROW_ID
1 1
1 2
1 3
2 1
2 2
3 1
3 2
如图所示,1重复3次,因此数字为1,2,3,然后再次以1开头
declare @table table (h_id int)
insert into @table
select 1
insert into @table
select 1
insert into @table
select 1
insert into @table
select 2
insert into @table
select 2
insert into @table
select 3
insert into @table
select 3
select h_id,d
from (select row_number() over(partition by h_id order by h_id ) as d,*
from @table) as source
参考您可以使用ROW_NUMBER()窗口函数
CREATE TABLE #ROW_TEST
(
H_ID INT
)
INSERT INTO #ROW_TEST
SELECT 1
UNION ALL SELECT
1
UNION ALL SELECT
1
UNION ALL SELECT
2
UNION ALL SELECT
2
UNION ALL SELECT
3
UNION ALL SELECT
3
SELECT H_ID,ROW_NUMBER() OVER (PARTITION BY H_ID ORDER BY H_ID) FROM #ROW_TEST
简单的rownumber将起作用
从表中选择h,row_number()(按h顺序按h划分)作为row_id
您是否尝试过row_number()
?SQL Server有许多使计算行号、百分位数或查找差距变得非常容易的功能。如果有人只使用了唯一没有此类功能的主流数据库,则SQL Server的排名和窗口功能会令人惊喜。没必要投反对票