表a
aid      Title   parentID
--------------------------
1 aa        0
2 bb  0
3 cc 10
4 ee 10
5 dd 10
6 ff 10
7 gg        9
8 hh  1
9 ii        0
10 jj       0
11 kk 10
12 ll 10
13 mm 10表bid    newstitle   aid     content
-------------------------------
1 aaa 3 aaa
2 bbb 3 aaa
3 ccc 3 aaa
4 ddd 4 aaa
5 eee 4 aaa
6 rrr 4 aaa
7 fff 5 aaa
8 ggg 5 aaa
9 hhh 5 aaa
10 iii 5 aaa
11 jjj 6 aaa
12 kkk 6 aaa
13 lll 7 aaa
14 mmm 7 aaa
15 nnn 8 aaa
16 ooo 8 aaa
17 ppp 11 aaa
18 qqq 12 aaa
19 sss 13 aaa
20 ttt 13 aaa
-------------------------------------
在表 a中 parentID=0的是父节点
不是0的时候为子节点
当父节点的aid=其他节点的parentID时
那些节点就是为改父节点的子节点
比如
3 cc 10
4 ee 10
5 dd 10
6 ff 10
就是
10 jj       0
的子节点==
而表b 的 aid就是为表a的 aid
我现在要的结果是列出所有的父节点以及父节点中的字节点所包含的news的数目
如:
aid(父节点ID) title(父节点名称) newsNum(新闻数)
-----------------------------------------------------
1                aa                  2(对应aid=8 的数目)
2
9                
10               jj                  16(对应aid为3,4,5,6,11,12,13)如何写???谢谢各位了~~~

解决方案 »

  1.   


    create table #temp
    (
    aid int,
    newsNum int
    )
    declare @id int
    --- 遍历所有父节点
    declare cur cursor for select aID from a where parentid = 0
    open cur
    fetch next from cur into @id
    while @@fetch_status = 0
    begin
    --- 对每一个父节点的子节点集合到b表中取出记录总数
    insert into  #temp select @id as aid,count(*) as newsNum from b where aid in 
    (select aid from a where parentid = @id)
    fetch next from cur into @id
    end
    close cur
    deallocate cur
    select a.aid,title,newsNum from #temp,a where a.aid = #temp.aid
    drop table #temp