0

有一个表如下:

Id   ||  ParentId ||  Other Columns ... 
=======================================
1    ||  1        || ...
2    ||  1        || ...
3    ||  1        || ...
1    ||  2        || ...
2    ||  2        || ...
3    ||  2        || ...
1    ||  3        || ...
2    ||  3        || ...

[Id]必须具有基于[ParentId](自己的编号)的自动增量值。

实现这一目标的最佳方法是什么?

4

2 回答 2

2

试试这个

select ROW_NUMBER() over(partition by parentId order by <any other column>) ID,
ParentId,<other columns>  
from  yourtable

编辑1:

如果您希望在 where 子句中使用 id

with cte as(                                
select ROW_NUMBER() over(partition by parentId order by <any other column>) ID,
ParentId,<other columns>  
from  yourtable)
select * from cte where ID=(some value)
于 2012-07-26T10:23:24.997 回答
0

演示

http://sqlfiddle.com/#!3/32645/6

更新了http://sqlfiddle.com/#!3/32645/13

create table dummy(parentId int)

insert into dummy values(1)
insert into dummy values(1)
insert into dummy values(2)
insert into dummy values(1)
insert into dummy values(4)
insert into dummy values(4)
insert into dummy values(5)
insert into dummy values(1)

select row_number() over (order by parentID) as ID,parentID from dummy
于 2012-07-26T10:10:36.723 回答