不一定5级用个函数实现
create function fn_GetInvitedCount(
@InviterID varchar(20)
)
returns int
as
begin
    declare @t table (UserId varchar(20))
    insert @t select UserId from A where InviterID=@InviterID
    while exists (select 1 from A
        where UserId not in (select UserId from @t)
        and  InviterID in (select UserId from @t)
        )
    insert @r
    select UserId from A
        where UserId not in (select UserId from @t)
        and  InviterID in (select UserId from @t)   declare @r int
   set @r=0
   select @r=count(*) from @t
   return @r
end
go--调用
select dbo.fn_fn_GetInvitedCount('inviter1')

解决方案 »

  1.   

    --调用2  从楼主举的例子看,最底层InviterID没在UsrtId出现select  InviterID,dbo.fn_fn_GetInvitedCount(InviterID)
    from a x
    where not exists (
    select 1 from a
    where userId=x.InviterID
    )
    group by InviterID
      

  2.   

    这个达不到5级吧?userid inviterid
    u1 i1
    u2 u1
    u3 i1
    u4 u3
    u5 u4@t
    userid inviterid
    u1 i1
    u3 i1这样的话u5就统计不到了吧?
      

  3.   


    不知道可以不可以写自调用的函数来实现? 不过sql里俺不会写.
      

  4.   

    Create table #user(UserID Int,
    InviterID int,
    Generation int
    )declare 
      @Generation int, 
      @UserID int
    set @UserID='要查寻的ID'
    set @Generation=0
    insert #user(userID ,InviterID,Generation)
    select  @userID,InviterID,@Generation from 存储数据的表
    WHILE @Generation<5
    Begin
    SET @Generation = @Generation + 1
    Insert #user(userID,InviterID,Generation)
      select m.userID
             m.InviterID
             @Generation
              from 存储数据的表 as m join #user
             on #user.Generation=@Generation-1
                and #user.usrID=m.InviterIDEnd