看看这个语句错误 怎么可以达到目的

jyganjun 2011-02-14 11:04:29
一个tree 结构 统计每个父的子类数量
SELECT [id], [title], [parent] (SELECT count(*) as b FROM [Experts_class] b where b.parent=aid) as Sub_munber FROM [Experts_class] a
...全文
58 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
jyganjun 2011-02-14
  • 打赏
  • 举报
回复
上面的仁兄 结合
SELECT [id], [title], [parent],
Sub_munber=(SELECT count(1) FROM [Experts_class] where id=a.parent)
FROM [Experts_class] a

这个排父子顺序的结构可以吗 谢谢
xccccccccccccc 2011-02-14
  • 打赏
  • 举报
回复
可以啊
jyganjun 2011-02-14
  • 打赏
  • 举报
回复
(爱新觉罗.毓华)

我需要子紧跟父的排序 要access 下的 可以吗
dawugui 2011-02-14
  • 打赏
  • 举报
回复
参考此例.
/*
标题:查询指定节点及其所有子节点的函数
作者:爱新觉罗·毓华(十八年风雨,守得冰山雪莲花开)
时间:2009-10-20
地点:陕西西安
地址:http://topic.csdn.net/u/20091020/18/a667c3dd-07e4-414d-9200-06c35d3d31a9.html
*/
ID parentid(下级级ID) 名称 数量
1 0 名称1 1
2 1 名称2 1
3 1 名称3 1
4 2 名称4 1
5 2 名称5 1
6 3 名称6 1
7 0 名称7 1
8 7 名称8 1
9 7 名称9 1

合计 6(名称1 以下所有节点 合计数量)
名称1 1
合计 3(名称2以下有节点)
名称2 1
名称4 1
名称5 1
合计 2
名称3 1
名称6 1


[code=SQL]
create table tb(ID int,parentid int, name varchar(10) ,cnt int)
insert into tb values(1 , 0 , '名称1' , 1)
insert into tb values(2 , 1 , '名称2' , 1)
insert into tb values(3 , 1 , '名称3' , 1)
insert into tb values(4 , 2 , '名称4' , 1)
insert into tb values(5 , 2 , '名称5' , 1)
insert into tb values(6 , 3 , '名称6' , 1)
insert into tb values(7 , 0 , '名称7' , 1)
insert into tb values(8 , 7 , '名称8' , 1)
insert into tb values(9 , 7 , '名称9' , 1)
go
--创建临时表
create table tmp (name varchar(10) ,cnt int)
go
--创建查询指定节点及其所有子节点的函数
create function f_cid(@ID int) returns @t_level table(id int , level int)
as
begin
declare @level int
set @level = 1
insert into @t_level select @id , @level
while @@ROWCOUNT > 0
begin
set @level = @level + 1
insert into @t_level select a.id , @level
from tb a , @t_Level b
where a.parentid = b.id and b.level = @level - 1
end
return
end
go

--创建存储过程并将数据插入临时表
create proc my_proc
as
begin
declare @id as int
declare @cnt as int
declare @name as varchar(10)
set @id = 0
while exists(select 1 from tb where id > @id)
begin
set @id = (select min(id) from tb where id > @id)
set @name = (select name from tb where id = @id)
set @cnt = (select sum(cnt) from (select a.* from tb a , f_cid(@id) b where a.id = b.id ) t)
insert into tmp select @name , @cnt
end
end
go
exec my_proc

select * from tmp

drop table tb , tmp
drop function f_cid
drop proc my_proc

/*
name cnt
---------- -----------
名称1 6
名称2 3
名称3 2
名称4 1
名称5 1
名称6 1
名称7 3
名称8 1
名称9 1

(所影响的行数为 9 行)

*/
[/code]
快溜 2011-02-14
  • 打赏
  • 举报
回复
你结贴率好低。
jyganjun 2011-02-14
  • 打赏
  • 举报
回复
谢谢 练习太少了 佩服
快溜 2011-02-14
  • 打赏
  • 举报
回复

SELECT [id], [title], [parent],
Sub_munber=(SELECT count(1) FROM [Experts_class] where id=a.parent)
FROM [Experts_class] a

快溜 2011-02-14
  • 打赏
  • 举报
回复

SELECT [id], [title], [parent],
Sub_munber=(SELECT count(1) FROM [Experts_class] where parent=a.id)
FROM [Experts_class] a

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧