Sql server 2008 r2 用于获取父子数据关系计数的SQL查询
我需要得到亲子关系的数量Sql server 2008 r2 用于获取父子数据关系计数的SQL查询,sql-server-2008-r2,Sql Server 2008 R2,我需要得到亲子关系的数量 QuestionID ParentQuestionID 207 NULL 208 NULL 209 207 210 208 211 209 212 210 例如,问题id 207具有子id 209&209具有子id 211。所以总共207有两个子ID。所以我想把count返回为2。我该怎么做呢。有人能帮忙吗?试试这个
QuestionID ParentQuestionID
207 NULL
208 NULL
209 207
210 208
211 209
212 210
例如,问题id 207具有子id 209&209具有子id 211。所以总共207有两个子ID。所以我想把count返回为2。我该怎么做呢。有人能帮忙吗?试试这个:
;with cte as
(
select QuestionID, ParentQuestionID, 0 as lvl
from questiontable
where QuestionID = 207
union all
select q.QuestionID, q.ParentQuestionID, lvl+1
from questiontable q
inner join cte c on c.QuestionID= q.ParentQuestionID
)
select count(*) from cte
where QuestionID <> 207
您可以使用参数而不是硬编码的值207,使其对任何问题ID都是动态的