62,254
社区成员
发帖
与我相关
我的任务
分享
create table table_A
(ID int, name int , type int, typeid int)
insert into table_A
select 1 , 1 , 1 , 0 union all
select 2 , 2 , 2 , 1 union all
select 3 , 3 , 3 , 2 union all
select 4 , 4 , 3 , 2
create table table_B
(ID int, name int , Aid int)
insert into table_B
select 1 , 1 , 3 union all
select 2 , 2 , 3 union all
select 3 , 3 , 4
select *,cnt =(select count(1) from table_B where aid =table_A.id) into #table3 from table_A where [type] =3;
select *,cnt=(select sum(cnt) from #table3 where typeid =table_A.id) into #table2 from table_A where [type] = 2;
select *,cnt=(select sum(cnt) from #table2 where typeid =table_A.id) into #table1 from table_A where [type] = 1;
select * from #table1
union all
select * from #table2
union all
select * from #table3
drop table #table1,#table2,#table3
ID name type typeid cnt
----------- ----------- ----------- ----------- -----------
1 1 1 0 3
2 2 2 1 3
3 3 3 2 2
4 4 3 2 1
declare @t table([ID] int, [name] int , [type] int , [typeid] int )
insert into @t values( 1 , 1 , 1 , 0 )
insert into @t values( 2 , 2 , 2 , 1 )
insert into @t values( 3 , 3 , 3 , 2 )
insert into @t values( 4 , 4 , 3 , 2 )
declare @t1 table([ID] int , [name] int , [Aid] int )
insert into @t1 values( 1 , 1 , 3 )
insert into @t1 values( 2 , 2 , 3 )
insert into @t1 values( 3 , 3 , 4 )
declare @TopLevel int
set @TopLevel = 1
select a.*,
( select count(*) from @t1 where [Aid] in(
select [id] from @t where type = a.Type and [id] = a.[id]
union
select [id] from @t where type = a.Type + 1 and [typeid] = a.[id]
union
select [id] from @t where type = a.Type + 2 and [typeid] in(
select [id] from @t where type = a.Type + 1 and [typeid] = a.[id])
)) as '数量'
from @t a where a.type in( @TopLevel , @TopLevel+1 , @TopLevel+2)