求一SQL语句,
在Sql Mobile下有一表
id name url pid
a 根 a root
b 子 a a
c 子 a a
d 根 b root
求一Select语句,能够查出满足条件的节点的子节点数。得到结果如下:
id name url pid subcounts
a 根 a root 2
d 根 b root 0
------解决方案--------------------看不明白!!
------解决方案--------------------create table T(id varchar(10), name varchar(10), url varchar(10), pid varchar(10))
insert T select 'a ', '根 ', 'a ', 'root '
union all select 'b ', '子 ', 'a ', 'a '
union all select 'c ', '子 ', 'a ', 'a '
union all select 'd ', '根 ', 'b ', 'root '
create function fun(@id varchar(10))
returns int
as
begin
declare @re int
select @re=count(*) from T where pid=@id
return @re
end
select *, subcounts=dbo.fun(id) from T
where pid= 'root '
--result
id name url pid subcounts
---------- ---------- ---------- ---------- -----------
a 根 a root 2
d 根 b root 0
(2 row(s) affected)
------解决方案--------------------select id, name, url, pid, subcounts=(select count(pid) from T where pid=a.id)
from T a
where a.pid= 'root '
------解决方案--------------------用group by 分组就可以