这是我的样本表结构,如何使用CTE这个
Create table #table(advId int identity(1,1),name nvarchar(100),ranks nvarchar(5),ReferId int ,ReferalRank nvarchar(5))
insert into #table(name,ranks,ReferId,ReferalRank) values('King','MGR',0,'0')
insert into #table (name,ranks,ReferId,ReferalRank) values('Maceij','MGR',1,'MGR')
insert into #table (name,ranks,ReferId,ReferalRank) values('Los','MGR',1,'MGR')
insert into #table (name,ranks,ReferId,ReferalRank) values('Los1','ADV',1,'MGR')
insert into #table (name,ranks,ReferId,ReferalRank) values('Griff','MGR',1,'MGR')
insert into #table (name,ranks,ReferId,ReferalRank) values('SA','MGR',2,'MGR')
insert into #table (name,ranks,ReferId,ReferalRank) values('CASSANDRA','MGR',2,'MGR')
insert into #table (name,ranks,ReferId,ReferalRank) values('Jason','MGR',3,'MGR')
insert into #table (name,ranks,ReferId,ReferalRank) values('Smith','MGR',3,'MGR')
insert into #table (name,ranks,ReferId,ReferalRank) values('Akee','MGR',6,'MGR')
insert into #table (name,ranks,ReferId,ReferalRank) values('Manasa','ADV',6,'MGR')
insert into #table (name,ranks,ReferId,ReferalRank) values('Akee','MGR',10,'MGR')
insert into #table (name,ranks,ReferId,ReferalRank) values('Manasa','ADV',10,'MGR')
select *from #table
让我对我的表结构 这里, ADVID 1个词语是由管理员提到, (2,3,4 ,5)是第一级1 (6,7,8,9)是第二级1 (10,11)是第三级1 (12,13)是第4级1 同样逻辑For每个顾问 Like This Structure
如何选择计数管理器(有多少管理者的代理下)对于每个顾问达3级
advId name CountOfmanager
1 king 8 --2,3,5,6,7,8,9,10
2 Maceij 3 --6,7,10
3 los 2 --8,9
4 Los1 0 -- nobody
5 Griff 0 -- nobody
6 SA 2 -- 10,12
7 CASSANDRA 0 -- nobody
8 Jason 0
9 Smith 0
10 Akee 1 --12
11 manasa 0
12 Akee 0
13 Manasa 0
这是我试过了。
with cte (advId,ReferId,Level)
as
(
select AdvId,ReferId,1 as Level from table where ReferId=1
union all
select a.AdvId,a.ReferId ,Level+1 from table
as a inner join cte as b on b.AdvId=a.ReferId
)
select COUNT(b.AdvId) From cte as a inner join table
as b on a.advId=b.advId where a.level<=3 and b.ranks='MGR'
我希望它清除,协助我得到的结果
的问题,为什么11不是2的一部分? 11已Refid 6 RefId 2。同样12和13也应该包括在计数为6,因为他们有ReferId 10其中有ReferId 6。 – 2014-10-31 08:02:53
其实我需要选择谁是'MGR'排名,11和13是'ADV'这就是为什么。 – 2014-10-31 09:36:22