Sql 相对于主键其余部分的自动增量id

Sql 相对于主键其余部分的自动增量id,sql,sql-server,tsql,Sql,Sql Server,Tsql,我有一张这样的桌子: | PK | Col Name | Type | |----+----------+------| | X | ParentId | int | X | Id | int 我试图将Id设置为标识,并且在父表上设置了ParentId。我希望数据是这样的: | ParentId | Id | |----------+----| | 1 | 1 | | 1 | 2 | | 1 | 3 | | 2 |

我有一张这样的桌子:

| PK | Col Name | Type |
|----+----------+------|
| X  | ParentId | int
| X  | Id       | int
我试图将
Id
设置为标识,并且在父表上设置了ParentId。我希望数据是这样的:

| ParentId | Id |
|----------+----|
| 1        | 1  |
| 1        | 2  |
| 1        | 3  |
| 2        | 1  |
| 2        | 2  |
| 3        | 1  |
但实际上它看起来像:

| ParentId | Id |
|----------+----|
| 1        | 1  |
| 1        | 2  |
| 1        | 3  |
| 2        | 4  |
| 2        | 5  |
| 3        | 6  |

事后看来,这是有道理的。是否可以通过某种方式实现所需的效果?

如果您只想从
ParentId
获得所需的输出,我还建议您使用以下方法:

select ParentId, 
ROW_NUMBER() OVER (PARTITION BY parentid order by parentid) as Id
from Foo

但如果仍要在表中使用,可以在表上创建
而不是INSERT
触发器,以下是可以使用的触发器:

create trigger dbo.trInsertFoo on dbo.Foo instead of insert
as begin
    insert into dbo.Foo
            (ParentId, Id)
    select  ParentId,
            Id =
            isnull( (select max(Id)
                    from    dbo.Foo
                    where   ParentId = i.ParentId), 0) +
            row_number() over (partition by ParentId order by (select 1))
    from    inserted i;
end;
上述触发器的简化版本

create trigger dbo.trInsertFoo on dbo.Foo instead of insert
as begin
    insert into dbo.Foo
            (ParentId, Id)
    select  ParentId,
            Id =
            (select isnull(max(Id), 0) + 1 from dbo.Foo where ParentId = i.ParentId)
    from    inserted i;
end;
但这一项不适用于批量插入,如:

INSERT INTO Foo (ParentId) VALUES (1), (1), (1), (2), (2), (3)`

标识始终是唯一的-因此,不,您不能有一个标识并且它具有相同的值,对不起。不要在子表上设置自动增量。而是在子表中的
ParentId
Id
上创建PK,然后手动或通过触发器填充其值。@dotNET,这正是我所期望的。我会去触发路线。真的,表名是“FOO”。@Charles-你查过我的答案了吗?问题解决了吗?