日期:2014-05-18  浏览次数:20604 次

如何实现 加入两个identity 的自增加
如何能够得到
例如
    ID       SUBID       NAME
    1         1               A
    1         2               B
    2         1               C
    2         2               D
    2         3               E
    2         4               F
    3         1               G
    3         2               H
    4         1               I
    4         2               J
    4         3               K
这样的结果 ID   和SUBID自动产生

------解决方案--------------------
create table t
( NAME varchar(10), Type1 int, Type2 int)
insert into t
select 'A ', 5, 2 union all
select 'B ', 5, 3 union all
select 'C ', 7, 1 union all
select 'D ' , 7, 2 union all
select 'E ', 7, 4 union all
select 'F ', 7, 7 union all
select 'G ', 9, 5 union all
select 'H ', 9, 6 union all
select 'I ', 11, 1 union all
select 'J ', 11, 3 union all
select 'K ', 11, 5

select id=(select count(distinct Type1) from t where Type1 <=a.Type1 ),
subid=(select count(*) from t where Type1=a.Type1 and Type2 <=a.Type2) ,
a.*
from t a


id subid NAME Type1 Type2
----------- ----------- ---------- ----------- -----------
1 1 A 5 2
1 2 B 5 3
2 1 C 7 1
2 2 D 7 2
2 3 E 7 4
2 4 F 7 7
3 1 G 9 5
3 2 H 9 6
4 1 I 11 1
4 2 J 11 3
4 3 K 11 5

(11 row(s) affected)